c# - 按下鼠标左键时更改鼠标光标?

标签 c# wpf mouse-cursor

我需要在按下鼠标左键时更改鼠标光标。不幸的是,在释放鼠标左键之前,对鼠标光标的更改将被忽略。有什么解决方法吗?感谢您的任何提示!

(我正在使用 WPF 和 C#)

编辑:

示例项目: http://cid-0432ee4cfe9c26a0.skydrive.live.com/self.aspx/%c3%96ffentlich/WpfApplication5.zip (只需运行它,说明显示在应用程序中)

示例代码:

XAML:

<Window x:Class="WpfApplication5.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="695" Loaded="Window_Loaded">
<Grid>
    <Button Content="Button1" Height="287" HorizontalAlignment="Left" Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" Width="235" />
    <Button Content="Button2" Height="287" HorizontalAlignment="Left" Margin="284,12,0,0" Name="button2" VerticalAlignment="Top" Width="278" MouseMove="button2_MouseMove" />
</Grid>

窗口类:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button2_MouseMove(object sender, MouseEventArgs e)
    {
        Cursor = Cursors.Cross;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        button1.Content="Step1: Left click on this button, \nhold down the left mouse button";
        button2.Content = "(Make sure you don't hover this\n button before hovering Button1.\n Default application cursor\n is the normal arrow cursor)\n\n Step 2: Keep on holding the left mouse \nbutton, hover this button\n\nThe cursor won't change. (It will change after the \nleft mouse button was released)";
    }
}

最佳答案

我建议在可能的情况下使用 Preview* 事件进行视觉更改,因为它可以很好地分离您的逻辑。此外,最好(恕我直言)使用 Mouse.OverrideCursor 属性临时更改光标。

例如:

void Window_Loaded(object sender, RoutedEventArgs e)
{
    // ...
    button1.PreviewMouseLeftButtonDown += Button1_PreviewMouseLeftButtonDown;
    button1.PreviewMouseLeftButtonUp += Button1_PreviewMouseLeftButtonUp;
}

void Button1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Mouse.OverrideCursor = Cursors.Cross;
    Mouse.Capture(button1);
}

void Button1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    Mouse.Capture(null);
    Mouse.OverrideCursor = null;
}

关于c# - 按下鼠标左键时更改鼠标光标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2984154/

相关文章:

c# - 自动选择添加到 ObservableCollection 的项目

c# - WPF 中的 BUG?当 FlowDirection 为 RightToLeft 时,Adorner 中的 TextBlock 会显示反转文本

c# - 尝试将 XmlElementAttribute 分配给 .NET CF 下的自定义 IXmlSerializable 对象时出现 InvalidOperationException

c# - 在 C# 程序中使用用 C++ 编写的 DLL

c# - 遍历 LibGit2Sharp 中的差异变化

c# - Windows 窗体应用程序中的非抗锯齿手形光标

javascript - PixiJS - 如何在鼠标悬停时更改光标?

c# - 在 C# 中创建新对象时,{ } 的行为是否类似于 ( )?

c# - WPF 数据绑定(bind)堆栈面板

jquery - 可点击的 block 指针