Thursday, July 31, 2008

Setting System.Control.Window.WindowState = WindowState.Normal doesn't fire StateChanged event

I needed to monitor when one of my Xaml windows was set to "Normal" state and couldn't get the OnPropertyChanged event to fire. Apparently there is a bug that prevents it from firing and the window from becoming visible again if you hide it, as indicated here. I slightly modified the code and found a good place to call it from is by assigning a click event to anything that may set it back to Normal state (in my case a button here).

You'll basically want to assign this delegate to anything that does the actual state change or call the method after you make it. Button clicks, window focus events, other property changed events, etc.

I had plans for a more elaborate workaround that actually made it work the correct way, but I don't have the time right now and hopefully it'll be fixed soon (could be fixed in SP1, dunno).

private const int SW_RESTORE = 9;

[System.Runtime.InteropServices.DllImport("user32.dll")]

static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

private void StateChangedWorkaround()

{

this.btnLaunch.Click += delegate

{

if (this.Window != null)

{

if (this.Window.WindowState == WindowState.Normal)

{

this.Window.Visibility = Visibility.Visible;

ShowWindow(new System.Windows.Interop.WindowInteropHelper(this.Window).Handle, SW_RESTORE);

}

}

};

}

0 comments: