I'm writing a sample application that is both GDI and WPF. I have a WPF window that has a button with a click handler with the following body:
this.DialogResult = true;
This closes the WPF dialog as it should. However, when closing this dialog, there is no "fade" effect on Windows 7/Vista. Alternatively, using a GDI window, the fade works. I'm either doing something wrong or this is the default behavior when closing WPF windows. Additionally, using the X button to close performs the same unwanted behaviour.
Ideally, I'd like both types of windows to close with the same style. Has anyone else encountered this? Is this something easily fixed for all of my WPF windows?
EDIT: Ok so I noticed something very interesting. When the window to closed is not over the parent window (e.g. it's moved to a different monitor) and closed, the usual fade fires correctly! However, if the window to close is over the parent window, no fade开发者_开发问答 occurs. Lovely!
If your window is borderless,
<Window
xmlns="blahblahblah"
AllowsTransparency="True" WindowStyle="None">
you can likely get away with making a fade animation to transparent, and write a close event handler that calls the animation then completes the close. If the window has a border, I am pretty sure the border will stay there and will look wierd.
I've come up with a solution, although I think it's still quite the hack to actually have fade working. I also tested with a pure WPF application and the window will still only fade when not overlapping its parent window. If anyone has a better solution than the code below, please let me know!
public class WindowBase : Window
{
private bool hasFadeCompleted = false;
protected override void OnClosing(CancelEventArgs e)
{
if (this.hasFadeCompleted)
{
base.OnClosing(e);
return;
}
e.Cancel = true;
var hWnd = new WindowInteropHelper(this).Handle;
User32.AnimateWindow(hWnd, 1, AnimateWindowFlags.AW_BLEND | AnimateWindowFlags.AW_HIDE);
Task.Factory.StartNew(() =>
{
this.Dispatcher.Invoke(new Action(() =>
{
this.hasFadeCompleted = true;
this.Close();
}), DispatcherPriority.Normal);
});
}
}
public static class User32
{
[DllImport("user32.dll")]
public static extern bool AnimateWindow(IntPtr hWnd, int time, uint flags);
}
public static class AnimateWindowFlags
{
public const uint AW_HOR_POSITIVE = 0x00000001;
public const uint AW_HOR_NEGATIVE = 0x00000002;
public const uint AW_VER_POSITIVE = 0x00000004;
public const uint AW_VER_NEGATIVE = 0x00000008;
public const uint AW_CENTER = 0x00000010;
public const uint AW_HIDE = 0x00010000;
public const uint AW_ACTIVATE = 0x00020000;
public const uint AW_SLIDE = 0x00040000;
public const uint AW_BLEND = 0x00080000;
}
I'm still surprised that this hasn't been an issue for anyone else.
精彩评论