Dea*_*Doe 5 c# wpf cursor-position
第一次在这里提出问题时,由于某种原因,我在此处找到的解决方案似乎不起作用。当窗口变为活动状态时,我的应用程序需要设置鼠标位置。我已经设置了功能,但无法使光标属性起作用。由于某种原因,我不能真正使用Cursor.Position或任何东西。我原本希望访问聊天室以找到解决方案,但是显然我只有在20岁以后才能讲话。
所以我在这里问如何用类似的方法更改光标位置
this.Cursor.SetPosition(x,y);
谢谢您的帮助。
编辑:已经从这里尝试过作为测试:
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
Run Code Online (Sandbox Code Playgroud)
但是编译器抱怨当前,位置,剪辑,位置,大小
最终解决方案:
using System.Runtime.InteropServices;
...
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int X, int Y);
...
Point relativePoint = MouseCaptureButton.TransformToAncestor(this)
.Transform(new Point(0, 0));
Point pt = new Point(relativePoint.X + MouseCaptureButton.ActualWidth / 2,
relativePoint.Y + MouseCaptureButton.ActualHeight / 2);
Point windowCenterPoint = pt;//new Point(125, 80);
Point centerPointRelativeToSCreen = this.PointToScreen(windowCenterPoint);
SetCursorPos((int)centerPointRelativeToSCreen.X, (int)centerPointRelativeToSCreen.Y);
Run Code Online (Sandbox Code Playgroud)
您可以使用InteropServices它来轻松完成此操作:
// Quick and dirty sample...
public partial class MainWindow : Window
{
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int X, int Y);
public MainWindow()
{
InitializeComponent();
SetCursorPos(100, 100);
}
}
Run Code Online (Sandbox Code Playgroud)
只要确保您包含System.Runtime.InteropServices名称空间即可。还有很多其他方法,例如上面重复链接中指出的一种方法。使用最适合您的东西。
编辑:
根据注释中的每个请求,以下是使其成为应用程序窗口坐标系而不是全局坐标系的一种方法:
public partial class MainWindow : Window
{
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int X, int Y);
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SetCursor(200, 200);
}
private static void SetCursor(int x, int y)
{
// Left boundary
var xL = (int)App.Current.MainWindow.Left;
// Top boundary
var yT = (int)App.Current.MainWindow.Top;
SetCursorPos(x + xL, y + yT);
}
}
Run Code Online (Sandbox Code Playgroud)
我不认为您会这样做...但是只要确保Window在初始化阶段(在构造函数中)不要尝试获取坐标即可。等待它加载完毕,类似于上面的操作;否则,您可能会得到NaN一些值。
如果要将其限制在窗口范围内,一种简单的方法是将其添加System.Windows.Forms到引用中,并使用重复链接中提供的代码。但是,如果您想使用我的方法(全部关于个人喜好...我使用我喜欢的...并且我喜欢PInvoke),则可以在将x和和y位置SetCursor(..)传递给之前检查和SetCursorPos(..),类似于:
private static void SetCursor(int x, int y)
{
// Left boundary
var xL = (int)App.Current.MainWindow.Left;
// Right boundary
var xR = xL + (int)App.Current.MainWindow.Width;
// Top boundary
var yT = (int)App.Current.MainWindow.Top;
// Bottom boundary
var yB = yT + (int)App.Current.MainWindow.Height;
x += xL;
y += yT;
if (x < xL)
{
x = xL;
}
else if (x > xR)
{
x = xR;
}
if (y < yT)
{
y = yT;
}
else if (y > yB)
{
y = yB;
}
SetCursorPos(x, y);
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您的应用程序使用Windows外观,则可能需要考虑边框。
| 归档时间: |
|
| 查看次数: |
13531 次 |
| 最近记录: |