如果光标位于特定的文本框中,则单击按钮仅删除该文本框的文本

If the cursor is in a specific textBox, delete only that textBox text with a button click

我正在构建一个简单的计算器。我有三个文本框:textBox1(第一个操作数)、textBox2(第二个操作数)和 textBox3(结果)。我有许多可以执行的操作数函数。我还有一个按钮可以清除所有字段以及其他功能。

我很难理解仅当光标位于该文本框中时才使用按钮删除特定文本框中的文本所需的代码。

例如:如果光标在 textBox1 中,按钮只会清除该文本框。

非常感谢任何帮助。

谢谢。

在这种情况下,您必须在文本框中使用重点 属性。 但是你需要做一个循环来识别哪个文本框被聚焦。

喜欢:

var focusedControl;
foreach(var control in this.Controls)
{
    if(control is TextBox)
    {
        if(control.Focused)
        {
           focusedControl = control;
           break;
        }
    }
}

您可以使用事件:"MouseHover" 或 "MouseClick" 并设置 textBox1.Text=""

单击 Button 时,它将获得焦点。

因此您需要跟踪您的 TextBoxes 中的哪个 最后

为此创建一个 class 级别变量:

TextBox focusedTextBox = null;

现在 这个事件与 Enter 事件 全部三个 TextBoxes:

private void textBoxes_Enter(object sender, EventArgs e)
{
    focusedTextBox = sender as TextBox;
}

那么这将只清除您的用户最后一个:

private void buttonClearCurrent_Click(object sender, EventArgs e)
{
    if (focusedTextBox != null) focusedTextBox.Text = "";
}