我们使用Windows桌面自动执行所有操作,并定期弹出一些第三方应用程序警告/异常框,同时我们可以检测并发送密钥代码(Enter)以关闭那些" OK"按钮,同样的方法可以把这些带到最前面,但关键代码(Enter,或Alt + F4)永远无法关闭它们模拟
这是代码
[DllImport("User32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
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);
}
}
Process[] pp = Process.GetProcesses();
... // qualifying the right handle assign to "p", debug shows it select the popup and set forefront (with focus).
hwnd = p.MainWindowHandle;
SetForegroundWindow(hwnd);
//Thread.Sleep(100); // thought needs some time to send key code before it's fully brought to forefront, but not matter.
PressKey(Keys.Enter, false);
PressKey(Keys.Enter, true);
//Thread.Sleep(100);
PressKey(Keys.Enter, false);
PressKey(Keys.Enter, true);
// following not working either
//PressKey(Keys.Alt, false);
//PressKey(Keys.F4, false);
//PressKey(Keys.Alt, true);
//PressKey(Keys.F4, true);
在调试过程中,当它们被带到最前面并且键码不起作用时,手动按ENTER或Alt + F4可以正常工作。我用Google搜索并尝试了在SO中找到的任何内容。