SendMessage in C#: Complete Guide
The SendMessage method in C# is used to send messages to the Windows operating system. It can send messages to specific windows, triggering corresponding events or operations. The SendMessage method is commonly used for interacting with Windows controls, such as sending text content to a text box or triggering a button click event.
Here is an example usage of the SendMessage method:
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
static void Main()
{
IntPtr hWnd = //获取窗口句柄的代码
uint WM_SETTEXT = 0x000C;
string text = "Hello, World!";
IntPtr ptr = Marshal.StringToHGlobalAuto(text);
SendMessage(hWnd, WM_SETTEXT, IntPtr.Zero, ptr);
}
}
In the example above, a static method named SendMessage is defined and the SendMessage function from user32.dll is imported using the DllImport attribute. After that, in the Main method, a message can be sent to a specified window using the SendMessage method. In this example, the text content of the window is set to “Hello, World!” using the WM_SETTEXT message.
It is important to note that the SendMessage method requires importing the System.Runtime.InteropServices namespace and understanding the constant values and corresponding operations of Windows messages. In practical usage, you can refer to the documentation or API references of Windows messages to obtain relevant information.