如何使用 C# SendKeys 以编程方式按下 Windows 按钮

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

How to press the Windows button programmatically using C# SendKeys

c#windowsbuttonsendkeys

提问by PentaPenguin

Basically I want to simulate in code a user clicking on the windows button. I know there is SendKeys which allows me to send key presses to windows if I get a handle to them, but what I can't figure out is what I need to get a handle on in order to send Windows button commands. E.g. Windows Button + L. Having read into this a bit it appears that CTRL-ESC should pop up the Start Menu also but not sure how to tell it to send the keys to Windows (if this is even possible). Any help would be much appreciated.

基本上我想在代码中模拟用户点击 Windows 按钮。我知道有 SendKeys 可以让我在我得到它们的句柄时将按键发送到 Windows,但我无法弄清楚我需要得到一个句柄才能发送 Windows 按钮命令。例如,Windows 按钮 + L。仔细阅读一下,似乎 CTRL-ESC 也应该弹出“开始”菜单,但不确定如何告诉它向 Windows 发送键(如果可能的话)。任何帮助将非常感激。

Cheers!

干杯!

回答by Dale

I don't think you can do this using SendKeys, you will need to p/invoke to an API function instead, probably keybd_eventto send either CTRL+ESC or the Windows key.

我不认为您可以使用 SendKeys 执行此操作,您将需要 p/invoke 到 API 函数,可能是keybd_event以发送 CTRL+ESC 或 Windows 键。

Hereis an example of opening the start menu this way in VB and hereis keybd_event with its C# signature on pinvoke.net.

是在 VB 中以这种方式打开开始菜单的示例,这里是 pinvoke.net 上带有 C# 签名的 keybd_event。

回答by Allon Guralnek

Some of the things that a user would do via a WinKey shortcut can be done programmatically in other ways. To take your WinKey+L example, you could instead just use the following statement:

用户通过 WinKey 快捷方式执行的某些操作可以通过其他方式以编程方式完成。以您的 WinKey+L 为例,您可以改为使用以下语句:

Process.Start("rundll32.exe", "user32.dll,LockWorkStation");

If you could elaborate on what exactly you're trying to accomplish, maybe there's a better way than keybd_event (as Dale has suggested).

如果你能详细说明你到底想要完成什么,也许有比 keybd_event 更好的方法(正如 Dale 所建议的那样)。

回答by Pete OHanlon

You need to use a global keyboard hook to hook into keyboards outside your application. There's an article on how to do it here.

您需要使用全局键盘挂钩来挂钩应用程序外部的键盘。这里有一篇关于如何做到这一点的文章。