Detect mouse location after Silverlight window loaded
I'm running a web page that has a SL 'box' in it.
I know how to use the MouseEnter and MouseLeave to detect if the mouse has entered the SL 开发者_StackOverflow社区box or left it.
My question is how to detect if the mouse is inside or outside the SL box when it has just loaded.
Thanks.
Gilad.
Here is a step-by-step post for building a Silverlight app that detects whether the mouse is over the Silverlight control when it is instantiated.
Step 1: Create a sample Silverlight application with Visual Studio (File / New Project / Silverlight Application)
Step 2: Edit the MainPage.xaml, and place the following code inside the UserControl's Grid:
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock x:Name="x_Text" Text="Mouse Was Not Over" />
</Grid>
Step 3: Edit the MainPage.cs, and replace the MainPage class with the following code:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
base.MouseEnter += OnMouseEnter;
base.Loaded += OnLoaded;
}
void OnMouseEnter(object sender, MouseEventArgs e)
{
x_Text.Text = "Mouse Was Over";
base.MouseEnter -= OnMouseEnter;
}
void OnLoaded(object sender, EventArgs e)
{
System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
timer.Interval = new TimeSpan(300 * TimeSpan.TicksPerMillisecond);
timer.Tick += delegate(object senderTick, EventArgs eTick)
{
base.MouseEnter -= OnMouseEnter;
timer.Stop();
};
timer.Start();
}
}
Step 4: Build and Run! Try it with the mouse over the center of the Silverlight control and outside of the control to see the results!
精彩评论