WPF c#获取passwordBox (x,y)位置的问题
本文关键字:位置 问题 获取 passwordBox WPF | 更新日期: 2023-09-27 18:03:01
下午好,
我需要得到PasswordBox的位置,这是放置在我的表单称为"LogInWindow"的某个地方。xaml",因为我想模拟物理/鼠标点击那个文本框。
我已经有了一个接受两个参数的函数,它正在执行click这些参数是x &Y应该是目标控件的位置,下面是函数:
public static void LeftMouseClick(int xpos, int ypos)
{
SetCursorPos(xpos, ypos);
mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
}
所以我在这里缺少的是xpos
和ypos
(目标控制的坐标),这是我试图获得位置的一种方法,但不幸的是它不起作用:
Point relativePoint = txtPassword.TransformToAncestor(Application.Current.MainWindow)
.Transform(new Point(0, 0));
我得到错误的txtPassword说:字段初始化器无法引用非静态字段、方法或属性"Main.LogInWindow"。txtPassword '
我最终通过遵循@FrancisLord的建议使其工作。
但现在我面临另一个问题,我想在另一台计算机/显示器上测试这个,我复制了我的。exe文件,我看到这在另一台机器上不起作用,在我的开发人员机器上,我看到我的功能LeftMouseClick
工作正常,因为它触发"button1",我正在寻找,而在另一台机器上看起来像它不模拟点击,也许它找不到button1的位置或任何东西://:///下面是我的代码:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
relativePoint = this.button1.TransformToAncestor(this)
.Transform(new Point(0, 0));
LeftMouseClick((int)relativePoint.X, (int)relativePoint.Y);
//restOFcode
}
它将通过错误查看您试图通过一个文件初始化器分配relativePoint
的值(即当您在其声明中将值设置为类级别变量时),如果它调用方法或属性,则无法执行此操作。你要做的就是像现在这样在类级别声明这个文件,但是在表单类的构造函数中赋值:
public class MyForm : Window
{
Point relativePoint;
public MyForm()
{
//other code already in the constructor
relativePoint = txtPassword.TransformToAncestor(Application.Current.MainWindow)
.Transform(new Point(0, 0));
}
}
PS:抱歉如果类名或继承没有意义,我不知道它应该是什么样子的WPF
使用这一行来获取窗口
的位置Point locationFromWindow = txtPassword.TranslatePoint(new Point(0, 0), Application.Current.MainWindow);
添加这行从屏幕获取位置
Point locationFromScreen = txtPassword.PointToScreen(locationFromWindow);