Windows Store apps with C# and relative mouse movement

Some times we want use the mouse as a more general input device. For example, a 3-D modeler might use mouse input to orient a 3-D object by simulating a virtual trackball; or a game might use the mouse to change the direction of the viewing camera via mouse-look controls.

In WinRT  there is Pointer instead mouse because we need to think in different devices : mouse, pen/stylus and touch.

In CoreWindow there are pointer events like PointerMoved, PointerPressed, PointerReleased, etc. You can handle PointerMoved event and track de Pointer. The problem is that, in PointerEventArgs, you have the absolute position of pointer in the screen.

To accomplish our goal we need relative mouse position. MouseMoved event is good choice. MouseEventArgs has MouseDelta propertie that gets a value that indicates the change in the screen location of the mouse pointer since the last mouse event.


Windows.Devices.Input.MouseDevice.GetForCurrentView().MouseMoved += Page_MouseMoved;

So,  next step is to hide the mouse pointer to simulate a camera moving around the object.


Window.Current.CoreWindow.PointerCursor = null;

Caution, now you don’t have mouse pointer and it cannot invoke edge UI such as the charms, back stack, or app bar. Therefore, it is important to provide a mechanism to exit this particular mode, such as the commonly used Esc key.

See an example:


private void Page_Loaded(object sender, RoutedEventArgs e)

{

Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;

ActivateMouseLook();

 }

private void Page_Unloaded(object sender, RoutedEventArgs e)
{

Window.Current.CoreWindow.KeyDown -= CoreWindow_KeyDown;
DeactivateMouseLook();
}

private void ActivateMouseLook()

{

Windows.Devices.Input.MouseDevice.GetForCurrentView().MouseMoved += Page_MouseMoved;

_baseCursor = Window.Current.CoreWindow.PointerCursor;

Window.Current.CoreWindow.PointerCursor = null;

}

private void DeactivateMouseLook()

{

Window.Current.CoreWindow.PointerCursor = _baseCursor;

Windows.Devices.Input.MouseDevice.GetForCurrentView().MouseMoved -= Page_MouseMoved;                                             }

}

void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
{
if (args.VirtualKey == VirtualKey.Escape)
  {
DeactivateMouseLook();
}
}
Advertisements

Deixa un comentari

Fill in your details below or click an icon to log in:

WordPress.com Logo

Esteu comentant fent servir el compte WordPress.com. Log Out / Canvia )

Twitter picture

Esteu comentant fent servir el compte Twitter. Log Out / Canvia )

Facebook photo

Esteu comentant fent servir el compte Facebook. Log Out / Canvia )

Google+ photo

Esteu comentant fent servir el compte Google+. Log Out / Canvia )

Connecting to %s