Trap mouse in WPF

蹲街弑〆低调 提交于 2019-12-04 19:12:19
Martin Liversage

A well-behaved application should not try to constrain the movement of the mouse pointer. It is the user and not your application the is in control and the behaviour you describe where the mouse pointer cannot move over the task bar when dragging a window isn't something I have experienced.

However, when the user drags the image in the canvas you can constrain the movement of the image so it stays inside the canvas even when the user moves the mouse pointer outside the canvas.

When doing a drag operation in Windows you normally capture the mouse. This means that your application keeps receiving information about the movement of the mouse pointer even when it moves outside your application window.

After more searching, I found there is a function in user32.dll called ClipCursor that does exactly what I want.

Here is an example of a sample app that traps the mouse cursor. When clicking Button1, the cursor will be constrained in a rectangle at (10,10,500,500). When pressing Button2 (or closing the app), the cursor will be free again.

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,41,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="button2_Click" />
    </Grid>
</Window>

CS:

[DllImport("user32.dll")]
static extern void ClipCursor(ref System.Drawing.Rectangle rect);

[DllImport("user32.dll")]
static extern void ClipCursor(IntPtr rect);

public MainWindow()
{
    InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    System.Drawing.Rectangle r = new System.Drawing.Rectangle(10, 10, 500, 500);
    ClipCursor(ref r);
}

private void button2_Click(object sender, RoutedEventArgs e)
{
    ClipCursor(IntPtr.Zero);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!