SendKey.Send()不工作(SendKey.Send() Not working)

2019-06-26 04:23发布

我使用WPF和我进口System.Windows.Form参考。 这里是我的代码:

Process[] process = Process.GetProcessesByName("wmplayer");
SetForegroundWindow(process[0].MainWindowHandle);
Thread.Sleep(200);
System.Windows.Forms.SendKeys.Send("^p");

Windows媒体播放器做焦点,但没有按键被接收。 为什么?

Answer 1:

您可以使用WinAPI的代替的SendKeys的:

[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
public static void PressKey(Keys key, bool up) {
    const int KEYEVENTF_EXTENDEDKEY = 0x1;
    const int KEYEVENTF_KEYUP = 0x2;
    if (up) {
        keybd_event((byte) key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr) 0);
    }
    else {
        keybd_event((byte) key, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr) 0);
    }
}

void TestProc() {
    PressKey(Keys.ControlKey, false);
    PressKey(Keys.P, false);
    PressKey(Keys.P, true);
    PressKey(Keys.ControlKey, true);
}


Answer 2:

在WPF应用程序,你必须使用SendKeys.SendWait() ( 英文文档 )来代替。

只是doublechecked它,而发送()正在为WinForms应用程序,WPF抛出虽然这两个目标.NET 4.0一个InvalidOperationException。

检查上面的链接以获取更多信息。



文章来源: SendKey.Send() Not working
标签: c# wpf forms