Zurb
Zurb

Reputation: 738

C# winforms application: event handler when returning (focus) from an external application

I have a winforms application which has to perform an action every time when returning from an external application (i.e. focus has been lost from my application, alt-tabbing to another program and then back).

Is there an application event handler for this?

I have looked into the activate and deactive handlers of a Form, but these handlers are also fired when my form receives focus back from itself (when closing a messagebox or closing a subform).

Upvotes: 2

Views: 757

Answers (2)

Cody Gray
Cody Gray

Reputation: 244682

Windows sends the WM_ACTIVATEAPP message to a window when it is being activated, and when it is being deactivated. So this is what you want to handle, specifically when wParam is TRUE (indicating activation).

WinForms does not wrap this as an event (at least not that I'm aware of), so you'll need to add the code to your form's window procedure manually:

public class MyForm : Form
{
    // other code

    protected override void WndProc(ref Message m)
    {
        const int WM_ACTIVATEAPP = 0x001C;
        switch (m.Msg)
        {
            case WM_ACTIVATEAPP:
            {
                if (m.WParam.ToInt32() != 0)
                {
                    // Your application's window is being activated, so
                    // do whatever it is you want. Or raise an event.
                    ...
                }
                break;
            }
        }
        base.WndProc(ref m);  // proceed with default processing
    }
}

Upvotes: 3

Jan V
Jan V

Reputation: 137

I would just set a bool value, you could lock the read/write part to make sure that the action is only called once.

Upvotes: 0

Related Questions