C# - 检测是否在我的表单外按下shift的最佳方法 [英] C# - Best way to detect if shift is pressed outside my form

查看:50
本文介绍了C# - 检测是否在我的表单外按下shift的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计,检测是否按下Control键或Shift键的最佳方法是什么,没有我的表格就在焦点上

解决方案

这是不可能的你使用.NET FCL,因为这不是真的需要。对于您的信息,焦点意味着键盘焦点,而不是其他任何东西。你在屏幕上看到的差异只不过是一个显示焦点的视觉线索。由于表单没有键盘焦点,根据定义它根本不接受键盘事件。



您仍然可以捕获键盘和分配给进程的许多其他事件除了你的应用程序,但是用纯C#是不可能的。它似乎是捕获此类事件的唯一方法,它是Windows Hook: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632589%28v=vs.85%29.aspx [ ^ ]。



那么,为什么你不能简单地用C#和P / Invoke安装这样的钩子?好吧,因为它必须是 Global Hook ,因为你需要在系统范围内捕获键盘事件。并且,根据Microsoft Hook文档,钩子函数应该驻留在单独的本机(非托管)DLL中。您可以创建此类DLL,但不能使用C#。然后,您可以开发一些机制来加载DLL并在此DLL和.NET应用程序之间进行通信。我使用非托管应用程序完成了这项工作,但使用.NET进行此操作并不是问题。



-SA


  if ((Control.ModifierKeys& Keys.Shift)!=  0 





如果shift键关闭,则为true ..


Hey guy, what is the best way to detect if Control key, or Shift key is pressed, without my form is on focus

解决方案

This is impossible if you use .NET FCL, because this is not really needed. For your information, "focus" means "keyboard focus" and nothing else. The difference you see on screen is no more than a visual clue to show the focus. As a form has no keyboard focus, it does not accept keyboard events at all, by definition.

You still can capture the keyboard and many other events dispatched to the processes other then your application, but it is impossible to do with pure C#. It looks like the only way to capture such event it the Windows Hook: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632589%28v=vs.85%29.aspx[^].

So, why cannot you simply install such hook with C# and P/Invoke? Well, because, it has to be the Global Hook, as you need to capture keyboard events system-wide. And, according to Microsoft Hook documentation, the hook function should reside in a separate native (unmanaged) DLL. You can create such DLL, but not using C#. Then you can develop some mechanism to load DLL and communicate between this DLL and your .NET application. I''ve done this with unmanaged application, but it''s not a problem to do it with .NET.

—SA


if ((Control.ModifierKeys & Keys.Shift) != 0)



This will be true if shift key is down..


这篇关于C# - 检测是否在我的表单外按下shift的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆