C#SendKeys.SendWait到另一个进程的对话框(notepad.exe)

我正在尝试在C#中执行以下操作:

  • 打开一个新进程(notepad.exe)
  • 输入一些文字(使用SendKeys)
  • 关闭记事本(处理任何确认对话框)

这就是我得到的

Process p = new Process(); p.StartInfo.Filename = "notepad.exe"; p.Start(); // use the user32.dll SetForegroundWindow method SetForegroundWindow( p.MainWindowHandle ); // make sure notepad has focus SendKeys.SendWait( "some text" ); SendKeys.SendWait( "%f" ); // send ALT+f SendKeys.SendWait( "x" ); // send x = exit // a confirmation dialog appears 

所有这一切都按预期工作,但现在我发送ALT + f + x后,我得到一个“你想保存更改为无标题”对话框,我想通过“按下”来关闭它在我的应用程序中’for“不要保存”。 然而

 SendKeys.SendWait( "n" ); 

仅当我的应用程序没有失去焦点时(ALT + f + x之后)才有效。 如果确实如此,我会尝试重新使用

 SetForegroundWindow( p.MainWindowHandle ); 

这会将焦点设置为主记事本窗口而不是确认对话框。 我使用了来自user32.dll的GetForegroundWindow方法,发现对话框句柄与记事本句柄不同(有点恍惚)但SetForegroundWindow甚至不能与对话框窗口句柄一起使用

知道如何将焦点重新放回对话框以便我可以成功使用SendKeys吗?

这是完整的代码

 [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow(); [DllImport("User32.DLL")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); public const int SW_RESTORE = 9; ... Process p = new Process(); p.StartInfo.FileName = "notepad.exe"; p.Start(); Thread.Sleep( 1000 ); SendKeys.SendWait( "some text" ); SendKeys.SendWait( "%f" ); // send ALT+F SendKeys.SendWait( "x" ); // send x = exit IntPtr dialogHandle = GetForegroundWindow(); System.Diagnostics.Trace.WriteLine( "notepad handle: " + p.MainWindowHandle ); System.Diagnostics.Trace.WriteLine( "dialog handle: " + dialogHandle ); Thread.Sleep( 5000 ); // switch to a different application to lose focus SetForegroundWindow( p.MainWindowHandle ); ShowWindow( dialogHandle, SW_RESTORE ); Thread.Sleep( 1000 ); SendKeys.SendWait( "n" ); 

谢谢

你无法提供你没有的东西 – 只有当你的应用程序具有焦点时, SetForegroundWindow()才有效。

现代Windows版本阻止应用程序窃取焦点,因为这是Windows 9x时代的一个主要烦恼。

此外,’Alt + F,x’仅指英文Windows版本上的退出,它不适用于大多数其他语言。 避免使用SendKeys() ,不可能以可靠的方式使用。