Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WPF, how do you tell if the left mouse button is currently down without using any events?

I have an app where I want to be able to move a slider. However, the slider is automatically updated by the program every 30 seconds. When I try to change the slider position with my mouse, the program is still updating the slider position, so I cannot move it manually with the mouse.

Somehow, I want the app to NOT update the slider if the user is in the process of changing its position. How can I tell if the left mouse button is down without using the left button down event? I just want to be able to access the mouse, and check the button state of the left mouse button. How do I access it without being inside of a mouse event?

like image 332
Curtis Avatar asked Apr 18 '13 14:04

Curtis


3 Answers

bool mouseIsDown = System.Windows.Input.Mouse.LeftButton == MouseButtonState.Pressed;
like image 114
DanW Avatar answered Nov 15 '22 16:11

DanW


There are some rare cases, where System.Windows.Input.Mouse.LeftButton does not work. For example during Resize.

Then you can use GetKeyState:

public enum VirtualKeyCodes : short
{
  LeftButton = 0x01
}

[DllImport("user32.dll")]
private static extern short GetKeyState(VirtualKeyCodes code);

public static bool CheckKey(VirtualKeyCodes code) => (GetKeyState(code) & 0xFF00) == 0xFF00;
like image 27
oleh Avatar answered Nov 15 '22 18:11

oleh


Ok,

I figured it out. The Slider control in WPF does NOT fire the MouseDown, LeftMouseDown, or LeftMouseUp events. This is because it uses them internally to adjust the value as the user is manipulating the slider. However, the Slider control in WPF DOES fire the PreviewLeftMouseDown and the PreviewLeftMouseUp events. In addition, when you click the Left Mouse button, the Slider Control automatically captures the mouse and holds on to it until you release the Left Mouse button.

I was able to solve my problem with the following 3 events:

   private void _sliderVideoPosition_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        _adjustingVideoPositionSlider = true;
        _mediaElement.Pause();
    }

    private void _sliderVideoPosition_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        _adjustingVideoPositionSlider = false;
        _mediaElement.Play();
    }

    private void _sliderVideoPosition_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
        if (_adjustingVideoPositionSlider)
        {
            _mediaElement.Position = TimeSpan.FromMilliseconds((int)e.NewValue);
        }
    }
like image 22
Curtis Avatar answered Nov 15 '22 16:11

Curtis