簡體   English   中英

在 WPF 中誘捕鼠標

[英]Trap mouse in WPF

我有一個 canvas ,其中有一個圖像。 我可以使用鼠標(拖放)移動該圖像。 我想阻止用戶將圖像移到 canvas 之外。

有什么辦法可以捕獲鼠標指針,使其只能在 canvas 內移動? 因此,當用戶試圖將鼠標移到 canvas 之外時,cursor 將保持在 canvas 的邊緣。

這種行為的一個例子是在移動 window 時,您不能在任務欄上移動它。 當您嘗試在任務欄上移動它時,鼠標 cursor 停留在任務欄的邊緣,拒絕在任務欄頂部移動。

表現良好的應用程序不應試圖限制鼠標指針的移動。 控制的是用戶而不是您的應用程序,您描述的拖動 window 時鼠標指針無法在任務欄上移動的行為不是我經歷過的。

但是,當用戶在 canvas 中拖動圖像時,您可以限制圖像的移動,使其保持在 canvas 內,即使用戶將鼠標指針移到 ZFCC790C72A86190DE1B549D0DDC.6F55CZ 之外

在 Windows 中進行拖動操作時,通常會捕獲鼠標 這意味着即使鼠標指針移出應用程序 window,您的應用程序也會繼續接收有關鼠標指針移動的信息。

經過更多搜索,我發現 user32.dll 中有一個名為 ClipCursor 的 function 完全符合我的要求。

這是捕獲鼠標 cursor 的示例應用程序示例。 單擊 Button1 時,cursor 將被約束在 (10,10,500,500) 處的矩形中。 當按下 Button2(或關閉應用程序)時,cursor 將再次空閑。

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM