Simon
Simon

Reputation: 467

How to use SendMessage to paste something to a different window

I am using the following SendMessage function to send/paste text to a different application. But in that function I have to give the name of the window from the other application.

How can I change this to get the current active window and paste in the code there?

Code:

[DllImport("user32.dll")]  
public static extern int SendMessage(int hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPStr)] string lParam);  

[DllImport("user32.dll", SetLastError = true)]  
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);  

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

public const int WM_PASTE = 0x0302;

IntPtr windowHandle = FindWindow("NOTEPAD", null);  
IntPtr editHandle = FindWindowEx(windowHandle, IntPtr.Zero, "EDIT", null);  
string textToSendToFile = "Input here your text";
Clipboard.SetText("Test");
SendMessage((int)editHandle, WM_PASTE, 0, textToSendToFile); 

I also got this but I do not really know how to combine this with the code above...

[DllImportAttribute("user32.dll", EntryPoint = "GetForegroundWindow")]
public static extern IntPtr GetForegroundWindow();

[DllImportAttribute("user32.dll", EntryPoint = "GetWindowThreadProcessId")]
public static extern uint GetWindowThreadProcessId([InAttribute()] IntPtr hWnd, IntPtr lpdwProcessId);

IntPtr hWndForegroundWindow = GetForegroundWindow();
uint activeThreadID = GetWindowThreadProcessId(hWndForegroundWindow, IntPtr.Zero);

Upvotes: 1

Views: 3590

Answers (1)

David Heffernan
David Heffernan

Reputation: 612844

The WM_PASTE message does not use the parameters. It's just an instruction to the recipient to take the contents of the clipboard and paste them. So if you wish the recipient to do anything, you'll need to populate the clipboard first.

If you don't wish to pollute the clipboard, and you should not since it belongs to the user, then you can send an EM_REPLACESEL message passing the text in lParam.

If you want to find the window which the user is currently working on, use GetForegroundWindow.

However, rather than faking low level messages, best of all would be to use the automation API.

Upvotes: 1

Related Questions