I have a window shown via the ShowDialog
command that I want to close when the mouse leaves that window. However, when the cursor leaves by any of the edges highlighted in green (see below) the MouseLeave
event is not fired and the window isn't closed. If the cursor leaves by one of the edges highlighted in red the `MouseLeave event is fired and the window closes.
Window definition:
<Window x:Class="OutputDeviceView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
ResizeMode="NoResize"
WindowStyle="None"
ShowInTaskbar="False"
SizeToContent="WidthAndHeight"
Background="Gray"
KeyDown="Window_KeyDown"
MouseLeave="Window_MouseLeave">
Event handler:
/// <summary>
/// Handle the MouseLeave event. Close the window when the mouse leaves the window
/// </summary>
/// <param name="sender">The object sending the event</param>
/// <param name="e">The event arguments</param>
private void Window_MouseLeave(object sender, MouseEventArgs e)
{
e.Handled = true;
Close();
}
The code that opens the window:
var outputDevices = new OutputDeviceView(this, _viewModel.OutputDevices, _viewModel.OutputDevice, PointToScreen(Mouse.GetPosition(this)));
if (outputDevices.ShowDialog() == true)
{
_viewModel.OutputDevice = outputDevices.SelectedDevice;
}
Why isn't the MouseLeave
event firing in all cases?
It has something to do with how the window is displayed. This window is displayed via the ShowDialog
method, whereas the other windows which behave as expected are displayed using the Show
method. (Thanks to Mitra M for pointing that out)