WPF 中的窗口位置






4.41/5 (10投票s)
向您展示如何在 WPF 中更改窗口位置

引言
这是一个简单的应用程序,展示了如何在 WPF 中改变窗口位置。
这个机器人会永远跟随你的鼠标光标。
Using the Code
通过几个步骤,我们可以创建这个应用程序。
首先,我在 WPF 中创建了一个窗口 - 我使用 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>
然后,我们可以使用以下属性访问窗口位置
左侧
顶部
我添加了一些方法来使用光标位置来改变窗口位置
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;
}
就是这样。
历史
- 2008年12月13日:首次发布