在键入C#时获得关注 [英] Get Focus When Typing in C#

查看:78
本文介绍了在键入C#时获得关注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户开始输入内容时激活搜索文本框(即使文本框没有正确聚焦)。我已经将表单上的KeyPreview设置为true。然后在KeyDown事件处理程序中,我有:

I want to activate a search textbox when the user starts to type something (even if the textbox isnt focused right then). I have come as far as setting KeyPreview on the form to true. Then in the KeyDown event handler, I have this:

if(!searchTextBox.Focused)
{
    searchTextBox.Focus();
}



这几乎可行。文本框是聚焦的,但第一个键入的字母丢失了。我想这是因为文本框从来没有真正得到过这个事件,因为当它发生时并没有集中注意力。那么,有没有人有一个聪明的解决方案,我应该如何使这项工作?


This almost works. The textbox is focused, but the first typed letter is lost. I guess this is because the textbox never really gets the event, since it wasn''t focused when it happend. So, do anyone have a clever solution to how I could make this work like it should?

推荐答案

这个问题的一个解决方案是确保文本框永远不会丢失通过为Form Activate事件和TextBox Leave事件安装处理程序来集中注意力。

One solution to this problem would be to ensure that the textbox never loses focus by installing handlers for the Form Activate event and the TextBox Leave event.
private void MainForm_Activated(object sender, EventArgs e) {
  textBox1.Focus();
}

private void textBox1_Leave(object sender, EventArgs e) {
  textBox1.Focus();
}



Activated处理程序将确保在表单变为活动状态时始终为文本框提供焦点,并且Leave处理程序将保持这种方式。



Alan。


The Activated handler will ensure than the textbox is always given focus when the form becomes active and the Leave handler will keep it that way.

Alan.


你不能;这毫无意义。非常正式地说,开始输入意味着只有控件已经集中时才会发生。为什么没有意义?因为对于当前关注的控件,这些键盘事件也可能意味着什么。



-SA
You cannot; and it makes no sense. "Starts to type", quite formally, means something which happens only if a control is already focused. Why does not make sense? Because for a currently focused control these keyboard events may also mean something.

—SA


这篇关于在键入C#时获得关注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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