2010-06-06 105 views
3

我需要在按住鼠標左鍵的同時更改鼠標光標。不幸的是鼠標光標的改變被忽略,直到釋放鼠標左鍵。有沒有解決這個問題的方法?感謝您的任何提示!按住鼠標左鍵時更換鼠標光標?

(我使用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)"; 
    } 
} 
+0

你使用MouseLeftButtonDown或MouseLeftButtonClick事件嗎? – Ozan 2010-06-06 13:50:07

+0

你好Ozan,我使用MouseLeftButtonDown。我在上面添加了一個示例。 – 2010-06-07 00:27:16

回答

7

我會建議使用預覽*事件,其中可能的視覺變化,因爲它會保持你的邏輯很好地分離。此外,最好(恕我直言)使用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; 
} 
+0

你好丹尼斯,非常感謝你的Mouse.OverrideCursor提示!它不適用於上面的示例(單擊按鈕後,沒有mousemove事件被觸發),但它適用於我的真實應用程序(在拖放饋送事件期間需要此操作;上面的示例是減少的示例,其中問題是另一個示例一:當鼠標左鍵關閉時,mousemove不會被觸發)。所以,雖然這不是我的示例的答案,但它仍然解決了我的問題:-) – 2010-06-07 09:15:08

+0

@Stefan:我用樣本進行了測試,但認爲MouseMove事件是您嘗試更改光標,所以我省略了它。 – Dennis 2010-06-07 12:31:47

+0

@Stefan:順便說一下,這是*不是*如何在拖放操作期間更改光標以提供用戶反饋。看看DragDrop.GiveFeedback和DragDrop.QueryContinueDrag事件(http://bit.ly/bbP14Y)。 – Dennis 2010-06-07 12:36:18

0

在鼠標左鍵向下處理程序,你可以有下面的代碼。

try 
{ 
    Cursor = Cursors.WaitCursor; 
} 
catch(Exception ex) 
{ 
} 
finally 
{ 
    Cursor = Cursors.Default; 
} 

您可以按照您的要求重置爲默認光標。