使用 C# 在 WPF 中设置鼠标指针位置的最佳方法是什么
我目前正在使用 SetCursorPos(int x, int y)
来设置光标在画布上的位置。这是我的代码,它从文本框中获取逗号分隔的坐标,并进行一些翻译以将其相对于我的画布进行转换。
if (e.Key == Key.Enter)
{
string[] s = setcoordinatesTB.Text.Split(", ".ToCharArray());
if (s.Length != 2) return;
int x,y;
bool r1 = int.TryParse(s[0], out x);
bool r2 = int.TryParse(s[1], out y);
if (!(r1 && r2)) return;
Point rel = canvas.TranslatePoint(new Point(x, y), window);
SetCursorPos( x + (int)window.Left + 10 + (int)rel.X, y + (int)window.Top + 32 + (int)rel.Y);
}
这里发生了奇怪的事情..不久前一切都工作正常..(我有另一个文本框,它使用 e.GetPosition(canvas)
连续显示相对于我的画布的光标坐标)。并输入所需的鼠标坐标。 &按回车键,两个文本框都显示相同的坐标(应该是)。但是现在,当我输入任何坐标时。 &按回车键,它会变成应有的两倍。即,输入 100,100 时,我的光标将变为 200,200(显示在第二个框中)。我将这些值除以 2 进行调整,但随后,光标转到另一个我无法解释的奇怪位置。
PS:如果有更好、更确定的方法来设置光标位置(即使它有很多麻烦),请发布它。
I'm currently using SetCursorPos(int x, int y)
to set the Cursor's position on my Canvas. This is my code which takes comma separated coordinates from a textbox and does some translation to convert it relative to my Canvas.
if (e.Key == Key.Enter)
{
string[] s = setcoordinatesTB.Text.Split(", ".ToCharArray());
if (s.Length != 2) return;
int x,y;
bool r1 = int.TryParse(s[0], out x);
bool r2 = int.TryParse(s[1], out y);
if (!(r1 && r2)) return;
Point rel = canvas.TranslatePoint(new Point(x, y), window);
SetCursorPos( x + (int)window.Left + 10 + (int)rel.X, y + (int)window.Top + 32 + (int)rel.Y);
}
Weird things are happening here..moments ago everything was working fine..(I have another text box which continuously displays cursor coordinates relative to my Canvas using e.GetPosition(canvas)
). and on typing the desired mouse coord. & hitting enter, both the Textboxes were displaying the same coord (which should be). But now, when I type any coord. & hit enter, it becomes double of what it should. i.e. on typing 100,100 my cursor goes to 200,200 (which shows in the 2nd box). I divided the values by 2 to adjust, but then, cursor goes to another weird location which I cannot explain.
PS: If there's a better, surer way to set the Cursor's position (even if it's got a lot of hassle associated), please post it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么第一个最明显的问题是——“不久前”和现在之间发生了什么变化?计算机软件通常不会在不改变某些内容的情况下改变其输出。
但为了帮助您调试,请尝试以下操作:
Well the first most obviouse question would be - what has changed between "moments ago" and now? Computer software usually doesn't change its output without something being altered.
But to help you debug, try out the following: