How to `SendKeys` to the last active input TextBox after clicking a button in winforms (C#)?

2

How to SendKeys to the last active input TextBox after clicking a button in winforms (C#)? I'm new to C# and I'm trying to create a winforms application with an on-screen keyboard and I have multiple textboxes.

I have searched and tried the guides I found, here's sample that's working so far.

below code is working when I focused the cursor outside (notepad, etc) my winforms app, but when I click on my created TextBox within the winforms app and then click a button to SendKeys to the TextBox, the cursor is being removed and focus is on the button I clicked, that is making the TextBox unfocused.

const uint WS_EX_NOACTIVATE = 0x08000000;
const uint WS_EX_TOPMOST = 0x00000008;

protected override CreateParams CreateParams
{
    get
    {
       CreateParams param = base.CreateParams;
       param.ExStyle |= (int)(WS_EX_NOACTIVATE | WS_EX_TOPMOST);
       return param;
    }
}

private void btnA_Click(object sender, EventArgs e)
{
    SendKeys.Send("A");
}

How can I return the cursor focus to the last active TextBox when I click a button to SendKeys to the TextBox?.

c#
winforms
keyboard
asked on Stack Overflow May 15, 2019 by Richard • edited Jan 8, 2021 by Richard

2 Answers

2

Call

_recentTextbox.Select();

before you do your sendkeys. There exists another method that will work similarly ( Focus() ) but that is primarily intended for people creating custom controls

If you have many textboxes and you need to know which one recently lost the focus to your button, attach the same Leave (or LostFocus) event handler to all the textboxes:

private void Leave(object sender, EventArgs e){
  _recentTextbox = (TextBox)sender; //_recentTextbox is a class wide TextBox variable
}

private void btnA_Click(object sender, EventArgs e)
{
   if(_recentTextbox == null)
     return;
   _recentTextbox.Select();
   SendKeys.Send("A");
   _recentTextbox = null; //will be set again when a textbox loses focus
}
answered on Stack Overflow May 15, 2019 by Caius Jard • edited May 15, 2019 by Caius Jard
0

// Optionally go to other field:

SomeOtherField.Focus();

// Add string at insertion point / over selected text:

SendKeys.Send("This is a test...");

The Send() method processes the string you passed immediately; to wait for a response from the program (like auto-populated database records matching input), use SendWait() instead.

answered on Stack Overflow May 15, 2019 by Shiva_Kishore

User contributions licensed under CC BY-SA 3.0