1
votes

I have a script written in Autoit that I am trying to convert over to C# to have more functionality with it down the road. The main functions it ends up having is to send text to a command (In-game text) to a game that I have open. What I am trying to do is get the same kind of functionality of the Send() function in Autoit.

I have been reading and have come to the conclusion that Postmessage and Sendmessage would be the best because they are able to send it to a window that is not currently active. Is there a way to send stings with PostMessage? I attempted to use Sendmessage and while it was sending key presses to the game some of them were not being accepted but post message seems to have them working.

Question: Is it possible to send strings and variable with Postmessage()? If so how?

Thanks! I'm still new to C# and trying to make the leap from a way simpler language. (Autoit)

2

2 Answers

0
votes

If you want to send keys (which is what I believe Send does in Autoit), you need to send the WM_KEYDOWN message and send the virtual keys as the wParam:

const UInt32 WM_KEYDOWN = 0x0100;
const int VK_A = 0x41;

[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

Then to use it, you need the window handle:

var windowHandle = System.Diagnostics.Process.GetProcessesByName("someprocess")[0].Handle;
PostMessage(windowHandle, WM_KEYDOWN, VK_A, 0);

A list of KeyCodes can be found here: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

0
votes

You cannot send strings between processes using PostMessage.

Because you are trying to send text across a process boundary, that text needs to be marshalled from the sender's process to the receiver's process. That would involve allocating a string on the heap of the receiving process. Because messages are delivered asynchronously, there would need to be a mechanism for the receiver of the message to free that marshalled string. But no such mechanism exists.

Even for synchronous messages delivered with SendMessage, only certain messages perform string marshalling. Only the messages that are defined by the system and designed to carry string payload perform cross-process marshalling. And even then, it's only the messages that are intended to be used cross-process. So you cannot use user-defined messages to send strings cross-process with SendMessage.

You will need to find a more capable IPC mechanism. Or send text character by character.