C#SendKeys.Send等待另一个进程的对话框(notepad.exe)

本文关键字:notepad exe 对话框 Send 等待 另一个 进程 C#SendKeys | 更新日期: 2023-09-27 18:24:47

我正在尝试在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 );

这将焦点设置为记事本主窗口,而不是确认对话框。我使用了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" );

感谢

C#SendKeys.Send等待另一个进程的对话框(notepad.exe)

您不能提供您没有的东西-只有当您的应用程序当前具有焦点时,SetForegroundWindow()才能工作。

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

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