Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trigger something whenever the WindowState changes in C#?

Tags:

c#

windowstate

So I want to instantly, as this portion of the program relies on speed, trigger a function when the windowstate is changed in my main form. I need it to be something like this:

private void goButton_Click(object sender, EventArgs e)
{
   //Code
}

I checked through the events tab of the form, I have no WindowStateChanged, etc. How do I do this?

The form will be resized a lot, so checking when the size changes won't work.

like image 703
Jon Avatar asked Sep 04 '12 01:09

Jon


2 Answers

The Resize event (or SizeChanged) will fire when the WindowState changes.


On a side note, WPF does include a StateChanged event for this directly.

like image 87
Reed Copsey Avatar answered Oct 12 '22 23:10

Reed Copsey


I hope i'm not too late for the party.

The way I chose to implement it is pretty straight forward and doesn't require allocating global variables, simply check the form's WindowState value before and after base.WndProc is called:

    protected override void WndProc(ref Message m)
    {
        FormWindowState org = this.WindowState;
        base.WndProc(ref m);
        if (this.WindowState != org)
            this.OnFormWindowStateChanged(EventArgs.Empty);
    }

    protected virtual void OnFormWindowStateChanged(EventArgs e)
    {
        // Do your stuff
    }

Bottom line - it works.

like image 29
Nissim Avatar answered Oct 12 '22 23:10

Nissim