天天看點

【WPF學習】第十七章 滑鼠輸入

  滑鼠事件執行幾個關聯的任務。當滑鼠移到某個元素上時,可通過最基本的滑鼠事件進行響應。這些事件是MouseEnter(當滑鼠指針移到元素上時引發該事件)和MouseLeave(當滑鼠指針離開元素時引發該事件)。這兩個事件都是直接事件,這意味着他們不使用冒泡和隧道過程,而是源自一個元素并且隻被該元素引發。考慮到控件嵌入到WPF視窗的方式,這是合理的。

  例如,如果有一個包含按鈕的StackPanel面闆,并将滑鼠指針移到按鈕上,那麼首先會為這個StackPanel引發MouseEnter事件(當滑鼠指針進入StackPanel面闆的邊界時),然後為StackPanel面闆引發MouseLeave事件。

  還可響應PreviewMouseMove事件(隧道路由事件)和MouseMove事件(冒泡路由事件),隻要移動滑鼠就會引發這兩個事件。所有這些事件都為代碼提供了相同的資訊:MouseEventArgs對象。MouseEventArgs對象包含當事件發生時辨別滑鼠鍵狀态的屬性,以及GetPosition()方法,該方法傳回相對于所選元素的滑鼠坐标。下面列舉一個示例,該例以裝置無關的像素顯示滑鼠指針在視窗中的位置:

private void MouseMoved(object sender, MouseEventArgs e)
        {
            Point pt = e.GetPosition(this);
            lblInfo.Text = string.Format("You are at ({0},{1}) in window coordinates", pt.X, pt.Y);
        }      

  在該例中,從客戶區(标題欄的下面)的左上角開始測量坐标。下圖顯示了上述代碼的運作情況。

【WPF學習】第十七章 滑鼠輸入

  XAML代碼如下所示:

<Window x:Class="MouseEvents.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300">
    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Rectangle Grid.Row="0" Name="rect" MouseMove="MouseMoved" Fill="LightBlue"></Rectangle>
        <TextBlock Name="lblInfo" Grid.Row="1"></TextBlock>
    </Grid>
</Window>      

一、滑鼠單擊

  滑鼠單擊事件的引發方式和按鍵事件的引發方式有類似之處。差別是對于滑鼠左鍵和滑鼠右鍵引發不同的事件。下表根據他們的發生順序列出了這些事件。除這些事件外,還有兩個響應滑鼠滾動動作的事件:PreviewMouseWheel和MouseWheel。

表 所有元素的滑鼠單擊事件(按順序排列)

【WPF學習】第十七章 滑鼠輸入

   所有滑鼠事件提供MouseButtonEventArgs對象。MouseButtonEventArgs類繼承自MouseEventArgs類(這意味着該類包含相同的坐标和按鈕狀态資訊),并添加了幾個成員。這些成員中相對不重要的是MouseButton(該成員用于通知是哪個滑鼠鍵引發的事件)和ButtonState(該成員用于通知當事件發生時滑鼠鍵時處于按下狀态還是釋放狀态)。ClickCount屬性更有趣,該屬性用于通知滑鼠鍵被單擊了多少次,進而可以區分是單擊(ClickCount的值是1)還是輕按兩下(ClickCount的值為2)。

  某些元素添加了更進階的滑鼠事件。例如,Control類添加了PreviewMouseDoubleClick事件和MouseDoubleClick事件,這兩個事件代替了MouseLeftButtonUp事件。以此類推,對于Button類,通過滑鼠或鍵盤可觸發Click事件。

二、捕獲滑鼠

  通常,元素每次接收到滑鼠鍵“按下”事件後,不久後就會接受到對應的滑鼠鍵“釋放”事件。但情況不見的總是如此。例如,如果單擊一個元素,保持按下滑鼠鍵,然後移動滑鼠指針離開該元素,這時該元素就不會接收到滑鼠鍵釋放事件。

  某些情況下,可能希望通過滑鼠鍵釋放事件,即使滑鼠鍵釋放事件是在滑鼠已經離開了原來的元素之後發生的。為此,需要調用Mouse.Capture()方法并傳遞恰當的元素以捕獲滑鼠。此後,就會接受到滑鼠鍵按下事件和釋放事件,直到再次調用Mouse.Capture()方法傳遞空引用為止。當滑鼠被一個元素捕獲後,其他元素就不會接收到滑鼠事件。這意味着使用者不能單擊視窗中其他位置的按鈕,不能單擊文本框的内部。滑鼠捕獲有時用于可以被拖放并可以改變尺寸的元素。

  有些情況下,可能由于其他原因(不是你的錯)丢失滑鼠捕獲。例如,如果需要顯示系統對話框,Windows可能會釋放滑鼠捕獲。如果當滑鼠鍵釋放事件發生後沒有釋放滑鼠,并且使用者單擊了另一個應用程式的視窗,也可能丢失滑鼠捕獲。無論哪種情況,都可以通過處理元素的LostMouseCapture事件來響應滑鼠捕獲的丢失。

  當滑鼠被一個元素捕獲時,就不能與其他元素進行互動(例如,不能單擊視窗中的其他元素)。滑鼠捕獲通常用于短事件的操作,如拖放。

  對前面一個示例進行修改,如下圖所示:

【WPF學習】第十七章 滑鼠輸入

 完整代碼如下所示:

【WPF學習】第十七章 滑鼠輸入
【WPF學習】第十七章 滑鼠輸入
<Window x:Class="MouseEvents.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300">
    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Rectangle Grid.Row="0" Name="rect" MouseMove="MouseMoved" Fill="LightBlue"></Rectangle>
        <Button Grid.Row="1" Name="cmdCapture" Click="cmdCapture_Click">Capture the Mouse</Button>
        <TextBlock Name="lblInfo" Grid.Row="2"></TextBlock>
    </Grid>
</Window>      

XAML

【WPF學習】第十七章 滑鼠輸入
【WPF學習】第十七章 滑鼠輸入
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MouseEvents
{
    /// <summary>
    /// MainWindow.xaml 的互動邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void MouseMoved(object sender, MouseEventArgs e)
        {
            Point pt = e.GetPosition(this);
            lblInfo.Text = string.Format("You are at ({0},{1}) in window coordinates", pt.X, pt.Y);
        }

        private void cmdCapture_Click(object sender, RoutedEventArgs e)
        {
            this.AddHandler(Mouse.LostMouseCaptureEvent, new RoutedEventHandler(LostMouseCapture));
            Mouse.Capture(rect);
            cmdCapture.Content = "[ Mouse is now captured ... ]";
        }
        protected void LostMouseCapture(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Lost capture");
            cmdCapture.Content = "Capture the Mouse";
        }
    }
}      

CS

三、滑鼠拖放

  拖放操作(是一種拖動資訊使其離開視窗中的某個位置,然後将其放到其他位置的技術)和前幾年相比現在不是非常普遍。程式設計人員已經逐漸地使用方法複制資訊,從人不在需要按住滑鼠鍵(許多使用者發現這一技術比較困難)。支援滑鼠拖放功能的程式通常将它用作為進階使用者提供的一種快捷方式,而不是一種标準的工作方式。

  本質上,拖放操作通過以下三個步驟進行:

  (1)使用者單擊元素(或選擇元素中的一塊特定區域),并保持滑鼠鍵為按下狀态。這是,某些資訊被擱置起來,并且拖放操作開始。

  (2)使用者将滑鼠移到其他元素上。如果該元素可接受正在拖動的内容的類型(例如一幅位圖或一塊文本),滑鼠指針會變成拖放圖示,否則滑鼠指針會變成内部有一條資訊的圖像。

  (3)當使用者釋放滑鼠鍵時,元素接收資訊并決定如何處理接收資訊。在沒有釋放滑鼠鍵時,可按下Esc鍵取消該操作。

  可在視窗中添加兩個文本框來嘗試拖放操作支援的工作方式。因為TextBox控件提供了支援拖放的内置邏輯。如果選中文本框中的一些文本,就可以将這些文本拖動到另一個文本框中。當釋放滑鼠鍵時,這些文本将移動位置。同一技術在兩個應用程式之間也可以工作——例如,可從Word文本中拖動一些文本,并放入到WPF應用程式的TextBox對象中,也可将文本從WPF應用程式的TextBox對象拖動到Word文檔中。

  有時,可能希望在兩個未提供内置拖放功能的元素之間進行拖放。例如,可能希望允許使用者将内容從文本框拖放到标簽中;或者可能希望建立如下圖所示的示例,該例允許使用者從Label對象或TextBox對象拖動文本,并放到另一個标簽中。對于這種情況,需要處理拖放事件。

【WPF學習】第十七章 滑鼠輸入

   拖放操作有兩個方面:源和目标。為了建立拖放源,需要在某個位置調用DragDrop.DoDragDrop()方法來初始化拖放操作。此時确定拖放操作的源,擱置希望拖動的内容,并指明允許什麼樣的拖放效果(複制、移動等)。

  通常,在響應MouseDown或PreivewMouseDown事件時調用DoDragDrop()方法。下面是一個示例,當單擊标簽時該例初始化拖放操作。标簽中的文本内容用于拖放操作:

private void lblSource_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label lbl = (Label)sender;
            DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Copy);
        }      

  接收資料的元素需要将它的AllowDrop屬性設定為true。此外,它還需要通過處理Drop事件來處理資料:

<Label Grid.Row="1" Grid.ColumnSpan="2" Background="LightGoldenrodYellow"
           VerticalAlignment="Center" HorizontalAlignment="Center" Padding="20"
      AllowDrop="True" Drop="lblTarget_Drop" DragEnter="lblTarget_DragEnter">To this Label</Label>      

  将AllowDrop屬性設定為true時,就将元素配置為允許任何類型的資訊。如果希望有選擇地接收内容,可處理DragEnter事件。這時,可以檢查正在拖動的内容的資料類型,然後确定所允許的操作類型。下面的示例隻允許文本内容——如果拖動的内容不能轉換成文本,就不能允許執行拖動操作,滑鼠指針會變成内部具有一條線的圖像光标,表示禁止操作:

private void lblTarget_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effects = DragDropEffects.Copy;
            else
                e.Effects = DragDropEffects.None;
        }      

  最後,當完成操作後就可以檢索并處理資料了。下面的代碼将拖放的文本插入标簽中:

private void lblTarget_Drop(object sender, DragEventArgs e)
        {
            ((Label)sender).Content = e.Data.GetData(DataFormats.Text);
        }      

  可通過拖放操作交換任意類型的對象。然而,如果需要和其他應用程式通信,這種自由的方法盡管很完美,卻是不明智的。如果希望将内容拖放到其他應用程式中,應當使用基本資料類型(如字元串、整型等),或者使用實作了ISerializable或IDataObject接口的對象(這兩個接口允許.NET将對象轉換成位元組流,并在另一個應用程式域中重新構造對象)。一個有趣的技巧就是将WPF對象轉換成XAML,并在其他地方重新構成該WPF對象。所需要的所有對象就是XamlWriter和XamlReader對象。

  拖放功能的完整代碼如下所示:

【WPF學習】第十七章 滑鼠輸入
【WPF學習】第十七章 滑鼠輸入
<Window x:Class="MouseEvents.DragAndDrop"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DragAndDrop" Height="300" Width="300">
    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <TextBox Padding="10" VerticalAlignment="Center" HorizontalAlignment="Center">Drag from this TextBox</TextBox>
        <Label Grid.Column="1" Padding="20" Background="LightGoldenrodYellow" 
           VerticalAlignment="Center"  HorizontalAlignment="Center"
           MouseDown="lblSource_MouseDown">Or this Label</Label>
        <Label Grid.Row="1" Grid.ColumnSpan="2" Background="LightGoldenrodYellow"
           VerticalAlignment="Center" HorizontalAlignment="Center" Padding="20"
      AllowDrop="True" Drop="lblTarget_Drop" DragEnter="lblTarget_DragEnter">To this Label</Label>
    </Grid>
</Window>      

DragAndDrop.xaml

【WPF學習】第十七章 滑鼠輸入
【WPF學習】第十七章 滑鼠輸入
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MouseEvents
{
    /// <summary>
    /// DragAndDrop.xaml 的互動邏輯
    /// </summary>
    public partial class DragAndDrop : Window
    {
        public DragAndDrop()
        {
            InitializeComponent();
        }
        private void lblSource_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label lbl = (Label)sender;
            DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Copy);
        }

        private void lblTarget_Drop(object sender, DragEventArgs e)
        {
            ((Label)sender).Content = e.Data.GetData(DataFormats.Text);
        }

        private void lblTarget_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effects = DragDropEffects.Copy;
            else
                e.Effects = DragDropEffects.None;
        }
    }
}      

DragAndDrop.xaml.cs

作者:Peter Luo

出處:https://www.cnblogs.com/Peter-Luo/

本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,并保留此段聲明,否則保留追究法律責任的權利。

繼續閱讀