C# Windows Forms计算器:实现选中文本框后输入数字
Hey there! Let's get your calculator working exactly how you want it—so when you click a number button, it only adds the digit to the TextBox you've previously selected. Here's a straightforward solution:
Basic Approach for a Single Number Button
Replace your existing button3_Click code with this:
private void button3_Click(object sender, EventArgs e) { // Check which TextBox is currently focused (selected by the user) if (textBox1.Focused) { // Append the digit to the end, or use SelectedText to insert at cursor position textBox1.Text += "1"; // Use this line instead if you want to insert at the selected spot: // textBox1.SelectedText = "1"; } else if (textBox3.Focused) { textBox3.Text += "1"; // textBox3.SelectedText = "1"; } }
How It Works
The Focused property tells us which TextBox the user actively selected (either by clicking it or tabbing into it). We check this property first, then only update the TextBox that has focus—no more digits showing up in both boxes at once!
Cleanup for Multiple Number Buttons
If you have buttons for all digits (0-9), you don't want to repeat the same logic in every button's click event. Instead, create a reusable method to keep your code tidy:
// Reusable method to handle any digit input private void AddDigitToFocusedTextBox(string digit) { if (textBox1.Focused) { textBox1.SelectedText = digit; } else if (textBox3.Focused) { textBox3.SelectedText = digit; } } // Wire up each number button to call this method private void button1_Click(object sender, EventArgs e) { AddDigitToFocusedTextBox("1"); } private void button2_Click(object sender, EventArgs e) { AddDigitToFocusedTextBox("2"); } // Repeat for buttons 0, 3-9 with their respective digits
This keeps your code DRY (Don't Repeat Yourself) and makes it way easier to adjust the behavior later if you need to tweak how digits are inserted.
内容的提问来源于stack exchange,提问作者Ace

