C#:当用户开始输入时激活一个文本框 [英] C#: Activate a TextBox when user starts typing

查看:246
本文介绍了C#:当用户开始输入时激活一个文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户开始键入内容时激活一个搜索文本框(即使文本框没有被聚焦)。我已经把表单上的 KeyPreview 设置为 true 。然后在KeyDown事件处理程序中,我有这样的:
$ b $ pre $如果(!searchTextBox.Focused)
{
searchTextBox.Focus();
}

这几乎可以奏效。文本框是重点,但第一个键入的字母丢失。我想这是因为文本框从来没有真正得到事件,因为它发生时没有集中。所以,有没有人有一个聪明的解决方案,我怎么可以使这项工作,应该如何?

我还想知道如何使这只发生在常规的键按下。所以不是像箭头键,修饰键,功能键等等。但是,我可能会想出一个办法。另一方面,我不太清楚我应该如何处理...

解决方案

作为一个除了从SDX2000回答,看看 MSDN文章的KeyDown事件。它也指 KeyPressed 事件,这是在KeyDown事件后触发的,我认为它更适合你想做的事情。



引用MSDN:


KeyPressEventArgs指定用户按下某个键时组成的字符。例如,当用户按SHIFT + K时,KeyChar属性返回一个大写的K。




  private void YourEventHandler(object Sender,KeyPressEventArgs Args)
{
if(!searchTextBox.Focused)
{
searchTextBox.Focus();
searchTextBox.Text + = Args.KeyChar;
//将脱字号移动到文本末尾,因为Focus()选择所有文本
searchTextBox.SelectionStart = searchTextBox.Text.Length
}
}

我其实不确定是否可以使用 + = 来附加一个字符串,所以你需要检查。我不知道当用户点击 return 时会发生什么情况,最好跟进这个问题。


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?

I would also like some tips to how make this only happen when regular keys are pressed. So not like, arrow keys, modifier keys, function keys, etc. But this I will probably figure out a way to do. The previous issue on the other hand, I am not so sure how I should tackle...

解决方案

As an addition to the answer from SDX2000, have a look at the MSDN article for the KeyDown event. It also refers to the KeyPressed event, which is fired after the KeyDown event, I think it is better suited for what you want to do.

Quoting MSDN:

A KeyPressEventArgs specifies the character that is composed when the user presses a key. For example, when the user presses SHIFT + K, the KeyChar property returns an uppercase K.

private void YourEventHandler(object Sender, KeyPressEventArgs Args)
{
    if(!searchTextBox.Focused)
    {
        searchTextBox.Focus();
        searchTextBox.Text += Args.KeyChar;
        // move caret to end of text because Focus() selects all the text
        searchTextBox.SelectionStart = searchTextBox.Text.Length
    }
}

I'm actually not certain that you can use += to append a char to a string, so you need to check on that. And I don't know what happens when the user hits return, better follow up an that issue as well.

这篇关于C#:当用户开始输入时激活一个文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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