简体   繁体   中英

How can i simulate Ctrl+link?

I tried to use SnedKeys:

SendKeys.SendWait("^" + "http://stackoverflow.com/");

What i want to do is to simulate the combination of Ctrl+link so it will open a new browser tab in the background. From the chrome document: "Press Ctrl and click a link Open the link in a new tab in the background"

I also tried before first:

SendKeys.Send("^" + "http://stackoverflow.com/");

But then getting exception:

InvalidOperationException

SendKeys cannot run inside this application because the application is not handling Windows messages. Either change the application to handle messages, or use the SendKeys.SendWait method.

The Ctrl+link only works if you are clicking on the mouse. Since you want to send keys, you need to use the appropriate keystrokes (Ctrl+N, then the url, then enter), so I would do this:

SendKeys.SendWait("^n");
SendKeys.SendWait("http://www.stackoverflow.com~");

The full code to test this (activating the window properly):

[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

// For Windows Mobile, replace user32.dll with coredll.dll
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, GetWindow_Cmd uCmd);

enum GetWindow_Cmd : uint
{
    GW_HWNDFIRST = 0,
    GW_HWNDLAST = 1,
    GW_HWNDNEXT = 2,
    GW_HWNDPREV = 3,
    GW_OWNER = 4,
    GW_CHILD = 5,
    GW_ENABLEDPOPUP = 6
}

private void button_Click(object sender, RoutedEventArgs e)
{

    IntPtr chromeWindow = FindWindow("Chrome_WidgetWin_1", null);
    IntPtr chrome = GetWindow(chromeWindow, GetWindow_Cmd.GW_HWNDNEXT);

    SetForegroundWindow(chrome);

    SendKeys.SendWait("^n");
    SendKeys.SendWait("http://www.stackoverflow.com~");
}

Note, I used the method described here on finding and activating the chrome window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM