How to inject text to the cursor focus

2019-08-29 08:34发布

问题:

I am developing a .NET windows app that needs to insert text in the place where the cursor is. The cursor will be in a different application that I have no control over. I think the operating system needs to be used here to achieve this. Can you help please?

回答1:

Put the text you want to insert into the clipboard

Find the window's handle:

Process[] processes = Process.GetProcessesByName("notepad");
foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    // Do something with the handle...
}

Send a "Ctrl+V" message to the window using pinvoke, see http://www.pinvoke.net/default.aspx/user32.SendMessage



回答2:

The most easy is to use the SendKeys class on Windows.Forms.

Otherwise use the SendMessage from the windows api to send key by key (some information on this).

Do not use the clipboard, the user typically does not want that, and does not expect that.