如何将 F4 键发送到 C# 中的进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/825651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I send the F4 key to a process in C#?
提问by Stefan Filip
I am starting a process from a Windows application. When I press a button I want to simulate the pressing of key F4in that process. How can I do that?
我正在从 Windows 应用程序启动一个进程。当我按下按钮时,我想模拟该F4过程中的按键按下。我怎样才能做到这一点?
[Later edit] I don't want to simulate the pressing of the F4key in my form, but in the process I started.
[稍后编辑] 我不想F4在我的表单中模拟按键的按下,但在我开始的过程中。
采纳答案by Patrick McDonald
To send the F4 key to another process you will have to activate that process
要将 F4 键发送到另一个进程,您必须激活该进程
http://bytes.com/groups/net-c/230693-activate-other-processsuggests:
http://bytes.com/groups/net-c/230693-activate-other-process建议:
- Get Process class instance returned by Process.Start
- Query Process.MainWindowHandle
- Call unmanaged Win32 API function "ShowWindow" or "SwitchToThisWindow"
- 获取 Process.Start 返回的 Process 类实例
- 查询 Process.MainWindowHandle
- 调用非托管 Win32 API 函数“ShowWindow”或“SwitchToThisWindow”
You may then be able to use System.Windows.Forms.SendKeys.Send("{F4}") as Reed suggested to send the keystrokes to this process
然后您可以使用 System.Windows.Forms.SendKeys.Send("{F4}") 作为 Reed 建议将击键发送到此进程
EDIT:
编辑:
The code example below runs notepad and sends "ABC" to it:
下面的代码示例运行记事本并向其发送“ABC”:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace TextSendKeys
{
class Program
{
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static void Main(string[] args)
{
Process notepad = new Process();
notepad.StartInfo.FileName = @"C:\Windows\Notepad.exe";
notepad.Start();
// Need to wait for notepad to start
notepad.WaitForInputIdle();
IntPtr p = notepad.MainWindowHandle;
ShowWindow(p, 1);
SendKeys.SendWait("ABC");
}
}
}
回答by Reed Copsey
回答by Marineio
You can focus the window (SetForegroundWindow WINAPI), and then use windows forms SendKeys to send F4.
你可以聚焦窗口(SetForegroundWindow WINAPI),然后使用windows窗体SendKeys发送F4。