본문 바로가기
Programming 개발은 구글로/C#[WPF]

C#[WPF] CaptureMouse

by 40대직장인 2022. 4. 18.

WPF MouseCature 

 

: 마우스 캡쳐를 실행하면 모든 마우스 관련 이벤트를 캡쳐한 컨트롤이 가져가며, 드래그 및 마우스 무브를 계속 따라갈 때 설정할 필요가 있습니다.

 

현재 작업 중인 프로그램에서, 마우스 움직임에 따라 윈도우의 로케이션(Volume Control)을 계속해서 움직일 필요가 있었습니다. 

그런데 마우스를 빠르게 움직여서 윈도우 바깥으로 보내면 MouseMove 이벤트가 이를 따라잡지 못하고 작동이 멈추거나 Delay가 발생하여 버벅거기는 현상이 발생이 됩니다.

 

이 때 CaptureMouse를 설정하니 빠르게 움직여도 모든 마우스 이벤트가 제가 설정한 윈도우로 들어오기 때문에 원하는 방식으로 정상동작이 되었습니다. 

 

※ References

http://msdn.microsoft.com/en-us/library/ms771301.aspx

 

C#
public bool CaptureMouse ();

마우스가 캡처되면 true이고, 그렇지 않으면 false입니다.

 

다음 예제에서는 마우스를 캡처(및 캡슐화 해제)하고 3D 모델을 보기 위한 특수 마우스 모드를 사용하도록 설정하는 마우스 및 키 입력 조합에 대한 처리기 쌍을 구현합니다.

 

C#
private void MouseDownHandler(object sender, MouseButtonEventArgs e)
{
    if (!Enabled) return;
    e.Handled = true;

    if (Keyboard.IsKeyDown(Key.F1) == true)
    {
        Reset();
        return;
    }

    UIElement el = (UIElement)sender;
    _point = e.MouseDevice.GetPosition(el);
    // Initialize the center of rotation to the lookatpoint
    if (!_centered)
    {
        ProjectionCamera camera = (ProjectionCamera)_slaves[0].Camera;
        _center = camera.LookDirection;
        _centered = true;
    }

    _scaling = (e.MiddleButton == MouseButtonState.Pressed);

    if (Keyboard.IsKeyDown(Key.Space) == false)
        _rotating = true;
    else
        _rotating = false;

    el.CaptureMouse();
}

private void MouseUpHandler(object sender, MouseButtonEventArgs e)
{
    if (!_enabled) return;
    e.Handled = true;

    // Stuff the current initial + delta into initial so when we next move we
    // start at the right place.
    if (_rotating == true)
    {
        _rotation = _rotationDelta * _rotation;
    }
    else
    {
        _translate += _translateDelta;
        _translateDelta.X = 0;
        _translateDelta.Y = 0;
    }

    //_scale = _scaleDelta*_scale;
    UIElement el = (UIElement)sender;
    el.ReleaseMouseCapture();
}

To be captured, an element must be enabled. Check whether IsEnabled is true before you call CaptureMouse.

If calling CaptureMouse returns true, then IsMouseCaptured is also true.

If calling CaptureMouse returns true, then the GotMouseCapture and IsMouseCapturedChanged events are raised, with RoutedEventArgs. Source in the event data reported as the element where the CaptureMouse method is called. If you force capture, you might interfere with existing captures - especially with captures that relate to drag-and-drop with the mouse.

To clear mouse capture from all elements, call Mouse.Capture with the element parameter provided as null.


※ References 

https://docs.microsoft.com/ko-kr/dotnet/api/system.windows.uielement.capturemouse?view=windowsdesktop-6.0 

 

댓글