为什么我的控件不接受键盘输入?
我已经构建了一个自定义控件,我正在尝试向其发送输入。它将接受鼠标输入并正确报告 MouseDown、MouseMove 和 MouseUp,但无论出于何种原因,它都不会接受键盘输入。当我单击它时,它不会获得焦点,并且我按下的任何键都会被已经获得焦点的任何控件解释。
这可能是非常简单的事情。我第一个想到的地方是 ControlStyle 属性,但我在帮助文件中看到的关于键盘输入的唯一内容是 csNoStdEvents,它禁用了它,而我的控件没有它。那么我需要做什么才能使我的控件能够接收输入焦点呢?
I've built a custom control that I'm trying to send input to. It will accept mouse input and report MouseDown, MouseMove and MouseUp correctly, but for whatever reason, it won't accept keyboard input. When I click on it, it doesn't receive focus, and any keys I press get interpreted by whatever control had the focus already.
This is probably something really simple. The first place I thought to look was in the ControlStyle property, but the only thing I can see in the helpfile about keyboard input is csNoStdEvents
, which disables it, and my control doesn't have that. So what do I need to do to make it so my control can receive input focus?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
需要尝试的一些事情:
MouseDown
上,调用Windows.SetFocus(Handle)
。根据我的经验,WinAPI 函数SetFocus
通常比 VCL 的SetFocus
方法效果更好。WM_GETDLGCODE
消息,回复Message.Result := Message.Result或DLGC_WANTCHARS或DLGC_WANTARROWS或DLGC_WANTTAB或DLGC_WANTALLKEYS
;A few things to try:
MouseDown
, callWindows.SetFocus(Handle)
. In my experience, the WinAPI functionSetFocus
often works better than the VCL'sSetFocus
method.WM_GETDLGCODE
message, reply withMessage.Result := Message.Result or DLGC_WANTCHARS or DLGC_WANTARROWS or DLGC_WANTTAB or DLGC_WANTALLKEYS
;难道就像鼠标按下时调用 SetFocus 一样简单吗?
Could it be as simple as calling SetFocus on mouse down?
您是否设置了
WS_TABSTOP
?我相信,如果没有它,你就没有输入焦点。但这是基于近十年前的回忆,当时我正在编写自己的语法高亮代码编辑器,但我早已丢失了它的源代码。{TWinControl.}TabStop := True;
应该这样做。一个快速测试应用程序具有从TWinControl
派生的不执行任何操作的组件,并显示关键事件的对话框,似乎表明它具有重要意义。Do you have
WS_TABSTOP
set? You don't have input focus without that, I believe. But this is based on a recollection from nearly 10 years ago, when I was writing my own syntax-highlighting code editor, for which I have long since lost the source.{TWinControl.}TabStop := True;
ought to do. A quick test app with a do-nothing component derived fromTWinControl
and displaying a dialog for key events seems to show that it makes all the difference.我已经检查了我的控件的代码,但看不到任何可能阻止此工作的内容。您在创建过程中调用“继承”吗?
我确实处理以下内容,但没什么特别的:
I've checked the code for my control and I can't see anything that might stop this working. Are you calling "inherited" in the Create procedure?
I do handle the following, but nothing special:
击键是否可以在表单级别使用?即KeyPreview是否开启,在窗体的OnKeypress事件中能否看到击键?您可以在调试器中跟踪它。该控件(如 Dan 所示)适合键盘输入吗?例如,TLabel 虽然显示文本,但却是图形控件。
Is the keystroke available at form level? That is, is KeyPreview turned on, and can you see the keystroke in the form's OnKeypress event? You can follow it from there in the debugger. Is the control (as Dan indicated) suitable for keyboard input? For instance, a TLabel, although it displays text, is a graphical control.