当按下鼠标左键时更改鼠标指针?

4
我需要在按下左键时改变鼠标指针。不幸的是,直到左键释放后,对鼠标指针的更改才会被忽略。有没有任何解决方法?感谢任何提示! (我正在使用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)";
    }
}

你正在使用 MouseLeftButtonDown 还是 MouseLeftButtonClick 事件? - Ozan
你好Ozan,我正在使用MouseLeftButtonDown。 我在上面添加了一个示例。 - stefan.at.kotlin
2个回答

8

我建议在可能的情况下使用预览事件来进行视觉上的更改,因为这将使您的逻辑保持良好的分离。此外,最好(在我看来)使用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;
}

你好Dennis,非常感谢你提供的Mouse.OverrideCursor提示!虽然它在上面的示例中不起作用(单击按钮后,没有触发mousemove事件),但它适用于我的实际应用程序(我需要在拖放givefeedback事件期间使用它;上面的示例是一个简化的示例,问题是另一个:当左鼠标键按下时,mousemove不会被触发)。因此,虽然这不是我的示例的答案,但它仍然解决了我的问题 :-) - stefan.at.kotlin
@Stefan:我已经用样例测试过了,但是我认为MouseMove事件是你试图改变光标的尝试,所以我省略了它。 - Dennis
@Stefan:顺便说一下,这不是更改光标以在拖放操作期间向用户提供反馈的正确方法。请查看DragDrop.GiveFeedback和DragDrop.QueryContinueDrag事件(http://bit.ly/bbP14Y)。 - Dennis
我正在使用GiveFeedback事件,但我是否仍然需要使用Mouse.OverrideCursor或者我错过了什么? - stefan.at.kotlin

0
在鼠标左键按下处理程序中,您可以编写以下代码。
try
{
   Cursor = Cursors.WaitCursor;
}
catch(Exception ex)
{
}
finally
{
   Cursor = Cursors.Default;
}

您可以根据需要将光标重置为默认值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接