-3

I am trying to make a very simple program, and I need to simulate a key press. I have tried to find a solution, but my program doesn't seem to know any of the methods that is suggested. I don't know if that is because I'm using a console aplication or what the deal is, but isn't there a simple what to send a virtual key press, that the computer will react to as if the user itself hit the button?

  • Your question is very poor in quality. Some more information regarding *exactly* what you are trying to accomplish is needed. – Sam Axe Jan 15 '14 at 01:21
  • "Simulating Key Press c#" downt wotk for me. In the answer by Thejaka Maldeniya, I found out that i needed to use System.Windows.Forms. But now i get that error I responded with. I simply need to simulate a key press. Say i wanted to simulate the space button for instance. If I'm in Word, it will make a space, if I'm in VLC, it will pause the video, if I'm in a game, I might jump. – user3026046 Jan 16 '14 at 13:50

1 Answers1

1

It's not clear whether you want to simulate key presses for your own application or a third-party application/window that happens to be running on the computer. I'll assume the latter.

The following minimal example will send Hello world! to one instance of notepad, which you have to start manually.

static void Main(string[] args)
{
    // Get the 'notepad' process.
    var notepad = Process.GetProcessesByName("notepad").FirstOrDefault();
    if (notepad == null)
        throw new Exception("Notepad is not running.");

    // Find its window.
    IntPtr window = FindWindowEx(notepad.MainWindowHandle, IntPtr.Zero,
        "Edit", null);

    // Send some string.
    SendMessage(window, WM_SETTEXT, 0, "Hello world!");
}

(full code)

It uses these PInvoke methods and constants:

[DllImport("user32.dll")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent,
    IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg,
    int wParam, string lParam);

private const int WM_SETTEXT = 0x000C;

Google is your friend when you want to learn more about how to get a handle on the application you want, PInvoke, and sending messages to other applications.

Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157