Controlling lost focus event when using keyboard shortcut
For both .NET Winforms and Windows Presentation Foundation, if I have a textbox where the user has just entered text and a button, if the user clicks the button, the "LostFocus" event fires before the button click raises the event. However, if the user uses a key combination for a button (for example, the button text is "& Button" or "_Button" and the user issues Alt + B), then the "LostFocus" event is fired after the button click event, which is less useful.
Do you know any reasonable workarounds? We have different things that we want to meet in LostFocus before ButtonClick.
You can try to track if the lost focus logic has occurred before triggering the button logic. In any case, you shouldn't have code right in the handler. You can do something like this:
public partial class Form1 : Form
{
private Boolean _didLostFocusLogic;
public Form1()
{
InitializeComponent();
}
private void textBox1_Leave(object sender, EventArgs e)
{
LostFocusLogic();
}
private void button1_Click(object sender, EventArgs e)
{
ButtonClickLogic();
}
private void LostFocusLogic()
{
/* Do stuff */
_didLostFocusLogic = true;
}
private void ButtonClickLogic()
{
if (!_didLostFocusLogic)
LostFocusLogic();
_didLostFocusLogic = false; // Reset for next time.
/* Do stuff */
}
}
source to share