Wiki


Wiki Table of Contents

Page Details

Published by:
This page has not yet been rated

Silverlight Tip of the Day #31: How to Detect Alt, Shift, Control, Windows and Apple keys with Left Mouse Down in Silverlight

Filed under: [Edit Tags]

 

Khi đang click trên ứng dụng Silverlight của bạn, bằng cách nào bạn biết được nếu nút <Alt>, <Shift>, <Ctrl>, <Windows> và / hay  <Apple> được nhấn tốt?

Để làm diều này, đơn giản bạn chỉ cần kiểm tra thành phần  Keyboard.Modifiers mà trả về một đối tượng ModifierKeys.

Đoạn mã sau được viết trong trang  Page.xaml.cs của chúng ta sẽ cho bạn biết bằng cách nào mà điều này được thực hiện.

Chạy và xem trước ứng dụng tại đây: http://silverlight.services.live.com/invoke/66033/Left%20Mouse%20Down/iframe.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
 
namespace ShiftMouseClick
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
 
            this.MouseLeftButtonDown += new MouseButtonEventHandler(Page_MouseLeftButtonDown);
        }
 
        void Page_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Data.Text = String.Empty;
 
            ModifierKeys keys = Keyboard.Modifiers;
 
            bool shiftKey = (keys & ModifierKeys.Shift) != 0;
            bool altKey = (keys & ModifierKeys.Alt) != 0;
            bool appleKey = (keys & ModifierKeys.Apple) != 0;
            bool controlKey = (keys & ModifierKeys.Control) != 0;
            bool windowsKey = (keys & ModifierKeys.Windows) != 0;
 
            if (true == shiftKey)
                Data.Text += "<shift>";
            if (true == altKey)
                Data.Text += "<alt>";
            if (true == appleKey)
                Data.Text += "<apple>";
            if (true == controlKey)
                Data.Text += "<ctrl>";
            if (true == windowsKey)
                Data.Text += "<windows>";
 
            Data.Text += " Left Clicked";
 
        }
    }
}

Và code trong trang  Page.xaml:

<UserControl x:Class="ShiftMouseClick.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="800" Height="600">
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="Data">Click here (also use alt,ctrl,windows,apple,shift keys)</TextBlock>
    </Grid>
</UserControl>

Thank you,
--Mike Snow

Recent Comments

Leave the first comment for this page.