我正在构建一个简单的WPF
应用程序。我有透明最大化 Window
和Canvas
(canvas1)。
我想在canvas1
或MainWindow
中获取鼠标位置(在这种情况下是相同的)。
为此,我使用此代码:
Point p = Mouse.GetPosition(canvas1); //and then I have p.X and p.Y
此代码适用于非透明 Canvas
。问题是我有一个透明 Canvas
,这段代码不起作用......(它不会给我错误,但坐标为p.X = 0
和p.Y = 0
)。
如何解决此问题?
答案 0 :(得分:2)
一种可能的解决方法是使用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.
答案 1 :(得分:1)
C#
using System.Windows;
using System.Windows.Input;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System;
using System.Windows.Threading;
namespace Test
{
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
internal struct Win32Point
{
public Int32 X;
public Int32 Y;
};
public static Point GetMousePosition()
{
Win32Point w32Mouse = new Win32Point();
GetCursorPos(ref w32Mouse);
return new Point(w32Mouse.X, w32Mouse.Y);
}
private double screenWidth;
private double screenHeight;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Width = screenWidth;
this.Height = screenHeight;
this.Top = 0;
this.Left = 0;
DispatcherTimer timer = new DispatcherTimer();
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
var mouseLocation = GetMousePosition();
elipse1.Margin = new Thickness(mouseLocation.X, mouseLocation.Y, screenWidth - mouseLocation.X - elipse1.Width, screenHeight - mouseLocation.Y- elipse1.Height);
}
}
}
XAML
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350" Width="525"
WindowStyle="None"
Topmost="True"
AllowsTransparency="True"
Background="Transparent"
ShowInTaskbar="False"
Loaded="Window_Loaded">
<Grid>
<Ellipse Width="20" Height="20" Fill="Red" Name="elipse1"/>
</Grid>
</Window>
解决!但到了晚:(