我正在尝试在 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 后,我得到一个“你想保存更改为无标题”对话框,我想通过“按”'n 从我的应用程序中关闭它' 代表“不保存”。然而
SendKeys.SendWait( "n" );
仅当我的应用程序没有失去焦点(在 ALT+f+x 之后)时才有效。如果确实如此,我会尝试使用
SetForegroundWindow( p.MainWindowHandle );
这会将焦点设置到记事本主窗口而不是确认对话框。我使用了GetForegroundWindow
user32.dll 中的方法,发现对话框句柄与记事本句柄不同(这有点道理),但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" );
谢谢