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

标签 c# .net sendkeys sharpdevelop

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

谢谢

最佳答案

您无法提供您没有的东西 - SetForegroundWindow() 仅当您的应用程序当前拥有焦点时才有效。

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

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

关于C# SendKeys.SendWait 到另一个进程的对话框 (notepad.exe),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9314524/

相关文章:

c# - 在 Visual Studio 2013 中构建失败并显示 "Could not copy the file.. because it was not found"

c# - 在所有库代码中禁用捕获上下文,ConfigureAwait(false)

.net - 如何提高 XML 读写性能

C# 屏幕分辨率和窗体显示

c# - SendKeys.SendWait 函数 - 向应用程序发送特殊 key

c# - .NET 将 key 发送到计算器

c# - CSharpFits : Writing FITS-file results in wrong image

c# - MySQL 数据读取器和复选框

c# - 如何将字符串转换为偶校验的 7 位 ASCII?

python - Selenium 发送 key 在 Ubuntu 上无法使用/