Basically what i want to do is to change a custom window's state from Maximized to Normal state and adjust the positions of the window, when user clicks and moves the mouse over TitleBar which is a simple border in my case.
The obvious thing to do is to attach an event-handler to MouseMove
and check if the mouse left button is pressed:
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Console.WriteLine("Mouse moved" + Mouse.Captured);
}
}
The problem is that the MouseMove
occurs when the mouse capture changes. So in my application the window will snap to a Normal
state after you open a popup and click the border, the snapping should happen after you start dragging.
Here is an XAML for the above code to prove the problem:
<Grid MouseMove="OnMouseMove" Background="AliceBlue">
<ComboBox Height="23">
<ComboBoxItem>Test1</ComboBoxItem>
<ComboBoxItem>Test1</ComboBoxItem>
<ComboBoxItem>Test1</ComboBoxItem>
<ComboBoxItem>Test1</ComboBoxItem>
<ComboBoxItem>Test1</ComboBoxItem>
<ComboBoxItem>Test1</ComboBoxItem>
</ComboBox>
</Grid>
Issue Steps, run the above code in debug:
- Click the
ComboBox
to open its popup. - Click on blue Grid (this will close the popup).
Notice: The Output window shows the Message "Mouse moved"
Expected behavior: Since only a click was made (there was no mouse move) i don't want the MouseMove
event.
I understand that the MouseMove
is fired when the Mouse.Captured
element changes and this is normal, but i need a way to distinguish between a normal MouseMove
and a MouseMove
caused by a Mouse Capture.
EDIT:
A more complex example of this issue can be found in MahApps.Metro demo. The steps are the same as described above - open a popup and click on title bar when the window is in Maximized state. You will notice the window snapped from Maximized state to normal state. This shouldn't have happened, since you did not double-click, or drag the title bar.
My solution so far:
Since i know this is caused by mouse captured element changes, i handled the LostMouseCapture
event and saved the mouse position:
private Point mousePositionAfterCapture;
private void OnLostMouseCapture(object sender, MouseEventArgs e)
{
mousePositionAfterCapture = e.GetPosition(this);
}
And in MouseMove
handler i check if the position has changed after last lost mouse capture:
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Point currentPossition = e.GetPosition(this);
if (currentPossition == mousePositionAfterCapture)
//means that the MouseMove event occurred as a result of
//Mouse Captured element change, we wait until an actual
//mouse move will occure
return;
Console.WriteLine("Mouse moved" + Mouse.Captured);
}
}