5

My objective is to get current position on the screen (out side the form), and save X, Y coords by press "C" for example.

I google and found some suggestion to use api hooks, but i wonder are there a way we can do this task purely in C# code (.NET Lib) ?

Please give me quick sample if possible because im new to c#.

Thanks

csano
  • 13,266
  • 2
  • 28
  • 45
Kelly
  • 195
  • 1
  • 2
  • 7

1 Answers1

9

Just use:

Cursor.Position

or

Control.MousePosition

To get the position. You can then map the KeyPress event of the form:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 'c')
        MessageBox.Show(Cursor.Position.ToString());
}

The individual X and Y coordinates are two properties of the Position object.

Documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position.aspx

MPelletier
  • 16,256
  • 15
  • 86
  • 137
  • I tested your code , but when i pressed "c key, MessageBox isn't appear. Am i missing something ? – Kelly May 29 '11 at 04:13
  • Maybe I went too fast. You say you're new to C#, but I don't know how new. Please forgive me if this is too basic, but did you add the KeyPress event in the form editor? – MPelletier May 29 '11 at 04:25
  • And of course KeyPress on form is a tricky thing, because if a control has the focus, then the event isn't fired. – MPelletier May 29 '11 at 04:27
  • 1
    Thanks MPelletier, i found the solution by set the Keypreview property = true for the form. regards. – Kelly May 29 '11 at 04:31
  • @Kelly And you just taught me about KeyPreview. Nice! – MPelletier May 29 '11 at 04:38