Silverlight Tip of the Day #6: Monitoring for Keyboard and Mouse Events.
[Blog Mirrored from https://silverlight.net/blogs/msnow/default.aspx]
Silverlight 2 provides full support for keyboard and mouse event handling. Not only can you monitor events for the entire application but you can also monitor them at the individual control level.
The following is an example of how to monitor all the keyboard and mouse events available at the application level:
Page.xaml.cs:
namespace SilverlightApplication
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
this.KeyDown += new KeyEventHandler(Page_KeyDown);
this.KeyUp += new KeyEventHandler(Page_KeyUp);
this.MouseEnter += new MouseEventHandler(Page_MouseEnter);
this.MouseLeave += new MouseEventHandler(Page_MouseLeave);
this.MouseLeftButtonDown += new MouseButtonEventHandler(Page_MouseLeftButtonDown);
this.MouseLeftButtonUp += new MouseButtonEventHandler(Page_MouseLeftButtonUp);
this.MouseMove += new MouseEventHandler(Page_MouseMove);
}
void Page_KeyDown(object sender, KeyEventArgs e)
{
}
void Page_KeyUp(object sender, KeyEventArgs e)
{
}
void Page_MouseEnter(object sender, MouseEventArgs e)
{
}
void Page_MouseLeave(object sender, MouseEventArgs e)
{
}
void Page_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}
void Page_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
}
void Page_MouseMove(object sender, MouseEventArgs e)
{
}
}
}
To monitor at the control level you can add an event handler directly to the control in the XAML. In the example below, we have added a mouse left down and mouse left up button event handler to a <Textblock> control.
Page.xaml:
<UserControl x:Class="SilverlightApplication6.Page"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="FPS" MouseLeftButtonDown="FPS_MouseLeftButtonDown"
MouseLeftButtonUp="FPS_MouseLeftButtonUp">Hello there</TextBlock>
</Grid>
</UserControl>
Page.xaml.cs:
namespace SilverlightApplication
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
}
private void FPS_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FPS.Text = "Mouse button down";
}
private void FPS_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
FPS.Text = "Mouse button up";
}
}
}
Thank you,
--Mike Snow
Comments
- Anonymous
November 18, 2008
PingBack from http://www.tmao.info/silverlight-tip-of-the-day-6-monitoring-for-keyboard-and-mouse-events/