public class Win32Helper
{
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// 發(fā)送消息
/// </summary>
/// <param name="hWnd"></param>
/// <param name="Msg"></param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
// 聲明常量
public const int WM_COPYDATA = 0x004A;
// 定義 COPYDATASTRUCT 結(jié)構(gòu)
[StructLayout(LayoutKind.Sequential)]
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
/// <summary>
/// 發(fā)送字符串消息
/// </summary>
/// <param name="hWnd"></param>
/// <param name="message"></param>
public static void SendMessageString(IntPtr hWnd, string message)
{
if (string.IsNullOrEmpty(message)) return;
byte[] messageBytes = Encoding.Unicode.GetBytes(message + '\0'); // 添加終止符
COPYDATASTRUCT cds = new COPYDATASTRUCT();
cds.dwData = IntPtr.Zero;
cds.cbData = messageBytes.Length;
cds.lpData = Marshal.AllocHGlobal(cds.cbData);
Marshal.Copy(messageBytes, 0, cds.lpData, cds.cbData);
try
{
SendMessage(hWnd, WM_COPYDATA, IntPtr.Zero, ref cds);
}
finally
{
//釋放分配的內(nèi)存,即使發(fā)生異常也不會泄漏資源
Marshal.FreeHGlobal(cds.lpData);
}
}
}