C# 使用 Sendkey 函数将密钥发送到另一个应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15292175/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:18:50  来源:igfitidea点击:

C# using Sendkey function to send a key to another application

c#sendkeys

提问by User2012384

I want to send a specific key (e.g. k) to another program named notepad, and below is the code that I used:

我想将一个特定的键(例如 k)发送到另一个名为记事本的程序,下面是我使用的代码:

private void SendKey()
{
    [DllImport ("User32.dll")]
    static extern int SetForegroundWindow(IntPtr point);

    var p = Process.GetProcessesByName("notepad")[0];
    var pointer = p.Handle;

    SetForegroundWindow(pointer);
    SendKeys.Send("k");
}

But the code doesn't work, what's wrong with the code?

但是代码不起作用,代码有什么问题?

Edited: Is it possible that I send the "K" to the notepad without notepad to be the active window? (e.g. active window = "Google chrome", notepad is in the backgound, which means sending a key to a background application)

编辑:我是否有可能将“K”发送到记事本而没有记事本作为活动窗口?(例如活动窗口=“谷歌浏览器”,记事本在后台,这意味着向后台应用程序发送密钥)

采纳答案by Mohammad Dehghan

If notepad is already started, you should write:

如果记事本已经启动,你应该写:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByNamereturns an array of processes, so you should get the first one (or find the one you want).

GetProcessesByName返回一组进程,所以你应该得到第一个(或找到你想要的)。

If you want to start notepadand send the key, you should write:

如果你想启动notepad并发送密钥,你应该写:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepadis started as Administrator and your application is not.

代码可能不起作用的唯一情况是当notepad以管理员身份启动而您的应用程序不是时。