C# - 检测打开上下文菜单时是否按住 SHIFT 键

C# - Detecting if the SHIFT key is held when opening a context menu(C# - 检测打开上下文菜单时是否按住 SHIFT 键)
本文介绍了C# - 检测打开上下文菜单时是否按住 SHIFT 键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 C# 应用程序中,我想显示一个上下文菜单,但如果在打开上下文菜单时按住 SHIFT 键,我想向菜单添加特殊选项.

In my C# application I want to display a context menu, but I want to add special options to the menu if the SHIFT key is being held down when the context menu is opened.

我目前正在使用 GetKeyState API 来检查 SHIFT 键.它在我的电脑上运行良好,但使用非英语 Windows 的用户说它根本不适合他们.

I'm currently using the GetKeyState API to check for the SHIFT key. It works fine on my computer but users with non-English Windows say it doesn't work at all for them.

我还读到,在打开上下文菜单时,在 Win32 API 中有一个标志,指示菜单中应显示 EXTENDEDVERBS.在 C# 中, Opening 事件的 EventArgs 不包含(据我所知)指示 EXTENDEDVERBS 的属性,或者是否有任何修饰键按下.

I also read that in the Win32 API when a context menu is opened there's a flag that indicates in the menu should show EXTENDEDVERBS. In C# the EventArgs for the Opening event doesn't contain (from what I can tell) a property indicating EXTENDEDVERBS or if any modifier keys are pressed.

这是我现在在Opening"事件中使用的代码:

Here's the code I'm using now inside the "Opening" event:

// SHIFT KEY is being held down
if (Convert.ToBoolean(GetKeyState(0x10) & 0x1000))
{
     _menuStrip.Items.Add(new ToolStripSeparator());

     ToolStripMenuItem log = new ToolStripMenuItem("Enable Debug Logging");
     log.Click += new EventHandler(log_Click);
     log.Checked = Settings.Setting.EnableDebugLogging;
     _menuStrip.Items.Add(log);
 }

如果 GetKeyState 是正确的做法,我的代码是否正确检测到按下的 SHIFT 键?

If GetKeyState is the right way of doing it, is my code properly detecting the SHIFT key being pressed?

推荐答案

您可以使用 ModifierKeys 静态属性 用于确定是否按住 shift 键.

You can use the ModifierKeys static property on control to determine if the shift key is being held.

if (Control.ModifierKeys == Keys.Shift ) { 
  ...
}

这是一个标志样式的枚举,但根据您的情况,您可能需要进行更严格的测试.

This is a flag style enum though so depending on your situation you may want to do more rigorous testing.

还请注意,这将检查在您检查值时是否按住 Shift 键.不是启动菜单打开的那一刻.这对您的应用程序可能没有显着差异,但值得注意.

Also note that this will check to see if the Shift key is held at the moment you check the value. Not the moment when the menu open was initiated. That may not be a significant difference for your application but it's worth noting.

这篇关于C# - 检测打开上下文菜单时是否按住 SHIFT 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)