Introduction
This is a simple application that shows how we can change window location in WPF.
This robot follows your cursor forever.
Using the Code
In a few steps, we can create this application.
First I created a window in WPF - I've done it with Expression Blend 2 SP1.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="CursorPosition.Window1"
x:Name="Window"
Title="Window1"
Width="85" Height="135"
AllowsTransparency="True" WindowStyle="None"
Background="{x:Null}"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Topmost="True">
<Grid x:Name="LayoutRoot">
<Image Margin="-23,0,-20,7" Source="Rbo rx2.png"
Stretch="Fill" RenderTransformOrigin="0.5,0.5">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="mamadScaleTransform"
ScaleX="1" ScaleY="1"/>
<SkewTransform AngleX="0" AngleY="0"/>
<RotateTransform Angle="0"/>
<TranslateTransform X="0" Y="0"/>
</TransformGroup>
</Image.RenderTransform>
</Image>
</Grid>
</Window>
Then we can access the window location with these properties:
I've added some methods to use cursor position for changing the window location:
public Window1()
{
this.InitializeComponent();
Timer timer = new Timer();
timer.Interval = 10;
timer.Tick += new EventHandler(timer_Tick);
timer.Enabled = true;
}
[DllImport("user32.dll")]
static extern bool GetCursorPos(ref System.Drawing.Point lpPoint);
float coefficient = 0.02f;
void timer_Tick(object sender, EventArgs e)
{
System.Drawing.Point mouseposition = new System.Drawing.Point();
GetCursorPos(ref mouseposition);
if (mouseposition.X < this.Left)
mamadScaleTransform.ScaleX = 1;
else
mamadScaleTransform.ScaleX = -1;
this.Left += (mouseposition.X - this.Left) * coefficient;
this.Top += (mouseposition.Y - this.Top) * coefficient;
}
That's all.
History
- 13th December, 2008: First post