views:

732

answers:

2

For both .NET Winforms and Windows Presentation Foundation, if I have a text box that the user has just entered text into, and a button, if the user clicks the button the "LostFocus" event fires before the button click event fires. However if the user uses a keyboard shortcut for the button (e.g. Button's text is "&Button" or "_Button" and user performs Alt+B), then the "LostFocus" event fires after the button click event, which is less useful.

Do you know of reasonable workarounds? We have various things that we want to occur in LostFocus before ButtonClick.

A: 

What would happen if you did this first of all in the button handler? (or perhaps subclass the button and override OnClick to apply this logic "worldwide").

Button b = (Button) sender;
b.Focus();

Would that get round the issue?

Quibblesome
+1  A: 

You could try tracking whether or not the lost focus logic has occured before firing the button logic. You shouldn't really have code directly in the handler anyway. You could 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 */
        }
    }
Jason Down