获取在画布上用透明背景鼠标位置 [英] Get mouse position on canvas with transparent background

查看:195
本文介绍了获取在画布上用透明背景鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个简单的 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.

这篇关于获取在画布上用透明背景鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆