65.9K
CodeProject is changing. Read more.
Home

Window Location in WPF

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.41/5 (10 votes)

Dec 13, 2008

CPOL
viewsIcon

61904

downloadIcon

2582

Shows you how we can change window location in WPF

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:

  • Left
  • Top

I've added some methods to use cursor position for changing the window location:

public Window1()
{
    this.InitializeComponent();
    
    // Insert code required on object creation below this point.
    Timer timer = new Timer();
    timer.Interval = 10;
    timer.Tick += new EventHandler(timer_Tick);
    timer.Enabled = true; 
}

//http://www.geekpedia.com/tutorial146_Get-screen-cursor-coordinates.html
[DllImport("user32.dll")]
static extern bool GetCursorPos(ref System.Drawing.Point lpPoint);
///
float coefficient = 0.02f;

void timer_Tick(object sender, EventArgs e)
{
    // New point that will be updated by the function with the current coordinates
    System.Drawing.Point mouseposition = new System.Drawing.Point();
    // Call the function and pass the Point, defPnt
    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