Get mouse position on canvas with transparent background

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

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

For this, I use this code:

 Point p = Mouse.GetPosition(canvas1); //and then I have pX and pY 

This code works great for an opaque Canvas . The problem is that I have a transparent Canvas , and this code does not work ... (This does not give me errors, but the coordinates are pX = 0 and pY = 0 ).

How can I fix this problem?

+2
c # wpf canvas
source share
2 answers

A possible workaround is to use the GetCursorPos Win32 function:

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

You need to convert the coordinates from pixels to points if you want to use them in WPF.

Usage example:

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

FROM#

  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> 

Solved! But until late: (

+1
source share

All Articles