15

I've found many articles on how to set the mouse position in a C# windows forms project - I want to do this in a console application. How can I set the absolute mouse position from a C# windows console application?

Thanks!

Hint: it's not Console.setCursorPosition, that only sets the position of the text cursor in the console.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
guywhoneedsahand
  • 185
  • 1
  • 1
  • 7
  • 3
    Why does your console application need to set the position of the Windows mouse cursor? This is quite an unusual situation to say the least. – Cody Gray - on strike Jul 16 '11 at 08:35
  • @Cody in fairness there are *very few* times you should control the mouse - it would be odd even if it was a windows app :) – Marc Gravell Jul 16 '11 at 08:36
  • As you have the solution can you share it with more code? I'm trying to do the same thing but I'm not very experienced with C# – npocmaka Jun 21 '14 at 20:04

4 Answers4

17

This is an old thread, but for the sake of completion it can be done this way...

use System.Runtime.InteropServices;

[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

then in method whatever position you wish e.g.

  SetCursorPos(500, 500);
Chaz
  • 2,311
  • 1
  • 12
  • 9
5

Fixed little mistake in Chaz unswer:

using System.Runtime.InteropServices;


namespace ConsoleImageWorker
{
    public static class Mouse
    {

        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);

        public static void SetCursorPosition(int x, int y)
        {
            SetCursorPos(x, y);
        }
    }
}

After that in any class you can just call:

Mouse.SetCursorPosition(100, 100);
Frees
  • 51
  • 1
  • 3
5

Inside your console application, add a reference to System.Windows.Forms.dll and use the other techniques you've read about. The choice of console vs windows exe only impacts the PE header (and maybe the default code template, but you can hack that trivially); you can still use the full framework in a console exe.

The mouse you want to control is in windows, not the console.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3

You can simply assign to Cursor.Position.

However, in a console application you will need to add references to the WinForms assemblies because console application projects do not include references to WinForms by default.

You will need to add System.Windows.Forms and System.Drawing, the latter to gain access to the Point class.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490