获取在画布上用透明背景鼠标位置鼠标、画布、透明、背景

2023-09-03 22:03:59 作者:戏如人生。

我建立一个简单的 WPF 应用程序。我有一个的透明最大化的窗口画布(canvas1)。

I am building a simple WPF application. I have a transparent maximized Window and a Canvas (canvas1).

我想在鼠标的位置 canvas1 主窗口(以这种情况下是同样的事情)。

I want to get the mouse position in canvas1 or in MainWindow (in this case is same thing).

有关这样做的我用这个code:

For doing this I use this code:

Point p = Mouse.GetPosition(canvas1); //and then I have p.X and p.Y

这code正常工作的非透明 画布。问题是,我有一个透明 画布,这code不工作...(它不给我错误,但坐标的pX = 0 PY = 0 )。

This code works fine for a non-transparent Canvas. The problem is that I have a transparent Canvas, and this code doesn't work... (It doesn't give me errors, but the coordinates are p.X = 0 and p.Y = 0).

我怎样才能解决这个问题?

推荐答案

一个可能的解决办法是使用 GetCursorPos Win32函数:

One possible workaround is to use GetCursorPos Win32 function:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetCursorPos(out System.Drawing.Point lpPoint); 

您必须坐标从像素点,如果你想用它在WPF转换。

You have to convert the coordinates from pixels to points if you want to use it in WPF.

用例:

System.Drawing.Point point;
if(!GetCursorPos(out point))
    throw new InvalidOperationException("GetCursorPos failed");
// point contains cursor's position in screen coordinates.
 
精彩推荐
图片推荐