单击按钮后关注文本框

Focusing on textBox after clicking a button

好的。因此,为了我的大学 class,我必须使用 Windows Forms 在 C# 中制作一个简单的计算器(使用 .Split() 做要求更高的版本)。有一个 textBox 和几个 buttons。所以f.e。我将数字 3 插入 textBox,但随后我想按 button,这会在我的数字后添加一个 + 符号。是的,它做到了。但是,如果我想回去写东西到我的textBox,我必须再次点击。

现在我找到了诸如使用 .Focus() 或使用 .Select() 之类的答案,它们可以工作,但不像我希望的那样,因为它们还标记了整个 textBox.text就像你用鼠标 select 它一样,蓝色,如果我按另一个数字,我会从 textBox 中删除所有内容。有没有办法在不标记整个文本的情况下做到这一点?

而不是只使用 .Focus() 去这个组合:

// Set focus to control
txtbox.Focus();
// Set text-selection to end
txtbox.SelectionStart = txtbox.Text.Length == 0 ? 0 : txtbox.Text.Length -1;
// Set text-selection length (in your case 0 = no blue text)
txtbox.SelectionLength = 0

// Set focus to control
txtbox.Focus();

// Check if text is longer then 0
if(txtbox.Text.Length > 0)
{
    // Set text-selection to end
    txtbox.SelectionStart = txtbox.Text.Length -1;
    // Set text-selection length (in your case 0 = no blue text)
    txtbox.SelectionLength = 0
}

两种方式都是一样的。在第一个中,我在第二行就地检查 text-length == 0

在第二个中,我使用了经典的if语句。