- 1 year ago
C# Windows forms Calculator - Selecting textbox per click
To select a specific TextBox
control upon clicking it in a Windows Forms Calculator application using C#, you can handle the Click
event for each TextBox
and programmatically set focus to the clicked TextBox
. Here's a step-by-step guide:
Create the Windows Forms Application:
Create a new Windows Forms application in Visual Studio.Add TextBox Controls:
Add the necessaryTextBox
controls to your form to represent the display and input fields for your calculator.Add Click Event Handlers:
For eachTextBox
that you want to be selectable on click, add aClick
event handler. You can do this by double-clicking theTextBox
in the designer or by manually writing the event handler code.For example, if you have two
TextBox
controls namedtextBoxDisplay
andtextBoxInput
, you can add event handlers like this:csharpprivate void textBoxDisplay_Click(object sender, EventArgs e)
{
textBoxDisplay.Focus();
}
private void textBoxInput_Click(object sender, EventArgs e)
{
textBoxInput.Focus();
}
Wire Up Event Handlers:
In the Form Designer, select eachTextBox
, go to the Properties window, and locate the "Events" section. Find theClick
event and select the corresponding event handler you created (e.g.,textBoxDisplay_Click
for thetextBoxDisplay
control).Testing:
Run the application and click on theTextBox
controls. The control you click on should receive focus and become selectable.
Here's a complete example of how the code might look:
csharpusing System;
using System.Windows.Forms;
namespace CalculatorApp
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void textBoxDisplay_Click(object sender, EventArgs e)
{
textBoxDisplay.Focus();
}
private void textBoxInput_Click(object sender, EventArgs e)
{
textBoxInput.Focus();
}
}
}
Remember that this example demonstrates how to select a specific TextBox
control when clicked. You can extend this concept to include more TextBox
controls as needed in your calculator application.