找出与最后焦点的控制 [英] Find out the control with last focus

查看:126
本文介绍了找出与最后焦点的控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#Windows窗体应用程序有几个文本框和一个按钮。我想找出具有焦点的文本框,并用它做什么。下面code,但它当然不会工作,因为该按钮会得到尽快关注,因为它是pressed我已经写了。

 私人无效button1_MouseDown(对象发件人,发送MouseEventArgs E)
{
    的foreach(在this.Controls控制T)
    {
        如果(T为文本框)
        {
            如果(t.Focused)
            {
                的MessageBox.show(t.Name);
            }
        }
    }
}
 

解决方案

有没有内置的属性或功能用于跟踪previous为重点的控制。就像你提到的,每当点击按钮,它会关注的焦点。如果你想保持跟踪的重点是在这之前的文本框,你将不得不自己做。

一个要对此将是一个类级变量添加到您的窗体拥有引用当前焦点文本框控件的方式:

 私人控制_focusedControl;
 

然后在的GotFocus 事件为每个文本框控件,你只需更新与 _focusedControl 变量该文本框:

 私人无效TextBox_GotFocus(对象发件人,EventArgs的)
{
    _focusedControl =(控制)发送;
}
 

现在,只要单击某个按钮(你为什么要使用的MouseDown 事件如你的问题,而不是按钮的点击事件),则可以使用参考previously为重点的TextBox控件保存在类级别的变量,只要你喜欢:

 私人无效的button1_Click(对象发件人,EventArgs的)
{
    如果(_focusedControl!= NULL)
    {
        //改变previously为重点的文本框的颜色
        _focusedControl.BackColor = Color.Red;
    }
}
 

I have a c# windows forms application with several textboxes and a button. I would like to find out the textbox which has focus and do something with it. I have written following code but of course it won't work because the button will get focus as soon as it is pressed.

private void button1_MouseDown(object sender, MouseEventArgs e)
{
    foreach (Control t in this.Controls)
    {
        if (t is TextBox)
        {
            if (t.Focused)
            {
                MessageBox.Show(t.Name);
            }
        }
    }
}

解决方案

There's no built in property or functionality for keeping track of the previous-focused control. As you mentioned, whenever the button is clicked, it will take the focus. If you want to keep track of the textbox that was focused before that, you're going to have to do it yourself.

One way of going about this would be to add a class-level variable to your form that holds a reference to the currently focused textbox control:

private Control _focusedControl;

And then in the GotFocus event for each of your textbox controls, you would just update the _focusedControl variable with that textbox:

private void TextBox_GotFocus(object sender, EventArgs e)
{
    _focusedControl = (Control)sender;
}

Now, whenever a button is clicked (why are you using the MouseDown event as shown in your question instead of the button's Click event?), you can use the reference to the previously-focused textbox control that is saved in the class-level variable however you like:

private void button1_Click(object sender, EventArgs e)
{
    if (_focusedControl != null)
    {
        //Change the color of the previously-focused textbox
        _focusedControl.BackColor = Color.Red;
    }
}

这篇关于找出与最后焦点的控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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