Refer the below sample code for your reference. Created click event which will check the last textbox active by the static property which gets sets on Lostfocus of textbox control and on click on any button to which click event is assigned will add the number to the textbox.
FormDesign View
C#
public partial class Form1 : Form
{
// Static property to maintain to check the textbox was active or not
public static bool isTextbox1Active = true;
public Form1()
{
InitializeComponent();
//Add event handler to txtNumber1 and txtNumber2 on LostFocus
txtNumber1.LostFocus += new EventHandler(TextBox_LostFocus);
txtNumber2.LostFocus += new EventHandler(TextBox_LostFocus);
btn1.Click += new EventHandler(btnClick);
btn2.Click += new EventHandler(btnClick);
btn3.Click += new EventHandler(btnClick);
btn4.Click += new EventHandler(btnClick);
btn5.Click += new EventHandler(btnClick);
btn6.Click += new EventHandler(btnClick);
btn7.Click += new EventHandler(btnClick);
btn8.Click += new EventHandler(btnClick);
btn9.Click += new EventHandler(btnClick);
btn0.Click += new EventHandler(btnClick);
}
// Click event to set the value in text box as per clicked button text and last active textbox
private void btnClick(object sender, EventArgs e)
{
string number = (sender as Button).Text;
if (isTextbox1Active)
{
txtNumber1.Text += number;
}
else
{
txtNumber2.Text += number;
}
}
// Create The Event to handle on lost focus of textbox
// To find last Active textbox control
private void TextBox_LostFocus(object sender, EventArgs e)
{
if ((sender as TextBox).Name == "txtNumber1")
{
isTextbox1Active = true;
}
else
{
isTextbox1Active = false;
}
}
}
VB.Net
Public Class Form1
' Static property to maintain to check the textbox was active or not
Public Shared isTextbox1Active As Boolean = True
Public Sub Form1()
InitializeComponent()
End Sub
' Click event to set the value in text box as per clicked button text and last active textbox
Private Sub btnClick(ByVal sender As Object, ByVal e As EventArgs) Handles btn0.Click, btn1.Click, btn2.Click, btn3.Click, btn4.Click, btn5.Click, btn6.Click, btn7.Click, btn8.Click, btn9.Click
Dim number As String = (TryCast(sender, Button)).Text
If isTextbox1Active Then
txtNumber1.Text += number
Else
txtNumber2.Text += number
End If
End Sub
' Create The Event to handle on lost focus of textbox
' To find last Active textbox control
Private Sub TextBox_LostFocus(ByVal sender As Object, ByVal e As EventArgs) Handles txtNumber1.LostFocus, txtNumber2.LostFocus
If (TryCast(sender, TextBox)).Name = "txtNumber1" Then
isTextbox1Active = True
Else
isTextbox1Active = False
End If
End Sub
End Class
Screenshot