我有一个带有几个文本框和一个按钮的c#windows窗体应用程序。我想找出具有焦点并对其做一些事情的文本框。我写了下面的代码,但当然它不起作用,因为按钮会在按下后立即获得焦点。
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);
}
}
}
}
答案 0 :(得分:16)
没有内置属性或功能来跟踪以前关注的控件。正如您所提到的,只要单击按钮,它就会成为焦点。如果你想跟踪之前关注的文本框,你将不得不自己动手。
解决此问题的一种方法是在表单中添加一个类级变量,该变量包含对当前焦点文本框控件的引用:
private Control _focusedControl;
然后在每个文本框控件的GotFocus
事件中,您只需使用该文本框更新_focusedControl
变量:
private void TextBox_GotFocus(object sender, EventArgs e)
{
_focusedControl = (Control)sender;
}
现在,每当点击一个按钮时(为什么你使用问题中显示的MouseDown
事件而不是按钮的Click
事件?),你可以使用之前关注的参考保存在类级变量中的文本框控件,但是您喜欢:
private void button1_Click(object sender, EventArgs e)
{
if (_focusedControl != null)
{
//Change the color of the previously-focused textbox
_focusedControl.BackColor = Color.Red;
}
}
答案 1 :(得分:3)
您可以订阅文本框的GotFocus事件,在字段中存储文本框(您可以使用sender参数),并在按下按钮时使用此字段?
答案 2 :(得分:2)
我会使用button1_MouseHover
事件。触发此事件后,ActiveControl
将指向上一个控件,您可以将其存储为_focusedControl
。
当然,如果用户选中该按钮,这将无效。
答案 3 :(得分:0)
private void BtnKeyboard_Click(object sender, EventArgs e)
{
if (MasterKeyboard.Visible)
{
btnKeyboard.ButtonImage = Properties.Resources._001_22;
MasterKeyboard.Visible = false;
_lastFocusedControl.Focus();
}
else
{
btnKeyboard.ButtonImage = Properties.Resources._001_24;
MasterKeyboard.Visible = true;
MasterKeyboard.BringToFront();
_lastFocusedControl.Focus();
}
}
private Control _lastFocusedControl;
private void BtnKeyboard_MouseHover(object sender, EventArgs e)
{
if (ActiveControl!=btnKeyboard)
_lastFocusedControl = ActiveControl;
}