c# - 在具有透明背景的 Canvas 上获取鼠标位置

标签 c# .net wpf canvas

我正在构建一个简单的 WPF 应用程序。我有一个透明最大化 Window 和一个Canvas (canvas1)。

我想在 canvas1MainWindow 中获取鼠标位置(在本例中是同一件事)。

为此,我使用以下代码:

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

此代码适用于非透明 Canvas。问题是我有一个transparent Canvas,这段代码不起作用...(它没有给我错误,但是坐标是 p.X = 0p.Y = 0)。

我该如何解决这个问题?

最佳答案

一种可能的解决方法是使用 GetCursorPos Win32 函数:

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

如果要在 WPF 中使用坐标,则必须将坐标从像素转换为点。

使用示例:

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

关于c# - 在具有透明背景的 Canvas 上获取鼠标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11737665/

相关文章:

c# - 检测粘贴事件是否发生在富文本框中

c# - IL 代码与 IL 程序集 : is there a difference?

c# - 构建逻辑

c# - 有没有更快的方法来克隆项目列表?

c# - Windows 应用商店应用程序中的 IObservableVector<T> 不能用作数据绑定(bind)源

c# - TargetFramework 更改后如何维护特定于语言的评论

c# - 如何忽略字符串比较中的空格?

c# - Entity Framework - 插入具有多个模型和数据库的实体

c# - 如何访问 ListBoxItems 的可见性属性

WPF MVVM如何在 View 更改后重新居中应用程序窗口?