Answered How to set the mouse position in wpf?

  • Monday, July 21, 2008 11:38 AM
     
     
    Hi,
    I can have the function to get the mouse position.
    Mouse.GetPosition();
    Like,
    How can i set Mouse Position?

All Replies

  • Monday, July 21, 2008 3:26 PM
     
     Answered
    WPF does not have an API for setting the mouse position. Use the Windows Forms method instead, or call the Win32 API directly.
    Controls for WPF and Windows Forms at http://www.divelements.co.uk
  • Wednesday, July 23, 2008 10:37 AM
    Moderator
     
     Answered Has Code
    Hi Ananda,

    I am posting some codes to elaborate the solution of Tim.
    To call Windows API from managed codes, we can declare the native method using System.Runtime.InteropServices.DllImportAttribute attribute.
    The following codes set the cursor to Point(300,300) related to parent window, when we start up our WPF Application Window.
            public Window1()  
            {  
                InitializeComponent();  
                NativeMethods.SetCursorPos(300, 300);  
            }  
     
            public partial class NativeMethods  
            {  
                /// Return Type: BOOL->int  
                ///X: int  
                ///Y: int  
                [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "SetCursorPos")]  
                [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]  
                public static extern bool SetCursorPos(int X, int Y);  
            } 


    Thanks,
    Ji

    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
  • Monday, October 26, 2009 3:24 AM
     
     
    how can we use this code in partial trusted zone.

    or, how to get the mouse position(out of window boundaries) in partial trusted zone.
  • Saturday, July 21, 2012 6:41 AM
     
     Proposed Has Code

    Here's a method that will move the mouse:

        public static void MoveCursor(int deltaX, int deltaY)
        {
            int x = System.Windows.Forms.Cursor.Position.X + deltaX;
            int y = System.Windows.Forms.Cursor.Position.Y + deltaY;
            System.Windows.Forms.Cursor.Position = new System.Drawing.Point(x, y);
        }
    

    If you just want to set the position, use:

        public static void MoveCursor(int x, int y)
        {
            System.Windows.Forms.Cursor.Position = new System.Drawing.Point(x, y);
        }
    

    • Proposed As Answer by andysheu Monday, April 15, 2013 7:50 AM
    •