确定非键盘事件方法调用中键盘的状态
在 textbox.TextChanged 事件中,如果仍按住某个键,我想阻止某些特定(处理器密集型)功能的执行。 例如,当用户通过按住删除键删除大块文本区域时,如果仍然按住删除键,我想防止代码触发。
我研究了 Control.ModifierKeys
这是谷歌搜索中最接近的东西,但在我的具体情况下,我想捕获是否按下了删除或退格键 - ModifierKeys 不提供。
有谁知道如何做到这一点? 理想情况下,我不需要跟踪每个文本框的 keyup/keydown 状态(尽管如果没有其他方法,我会这样做)
In a textbox.TextChanged event I want to prevent some specific (processor intensive) functionality from executing if a key is still held down. E.g. while the user is deleting large regions of text by holding down the delete key I want to prevent the code from firing if the delete key is still held down.
I looked into Control.ModifierKeys
which is the closest thing a google search kicks up, but in my specific case I want to trap if the delete or backspace key are pressed - which ModifierKeys doesn't provide.
Does anyone know how to do this? Ideally something which doesn't involve me having to track the state of keyup/keydown for each and every textbox (although if there is no other way I'll do it like that)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不处理 KeyUp 事件 而不是处理
KeyPress
。 这样你就可以始终确定该键已经被按下并且正在被...呃..释放(因为没有更好的词了!)Why not handle the KeyUp event instead of handling
KeyPress
. That way you can always be sure that the key has already been depressed and is in the process of being... errr.. released (for lack of a better word!)如果您想知道当前的键盘状态(通过 KeyPreview),您不能将事件附加到主窗体上吗?
然后检查文本框事件处理程序中存储的状态。
If your wanting to known the current keyboard state (via KeyPreview), can't you attach the event on the main form.
Then check against the stored state from the textbox event handler.
重写
Control.ProcessKeyPreview
应该可以做到。Overriding
Control.ProcessKeyPreview
should do it.最后,我求助于外部函数
GetKeyboardState
所以为了将来的参考,我正在做一些事情:
我不确定函数调用的开销,但我很确定它会小于该函数在不存在的情况下将执行的处理。
In the end I've resorted to the external function
GetKeyboardState
So for future reference i'm doing something along the lines:
I am not sure of the function call overhead, but I'm pretty sure it will be less than the processing the function would perform were it not there.