public class Message
{
public const int USER = 0x0400; // 對應 MFC WM_USER
public const int WM_TEST = USER + 101; // 應用程式自訂訊息
public const int WM_MSG = USER + 102; // DLL 傳遞訊息
}
在 MsgForm.cs 中宣告:
// 宣告 SendMessage API
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(
IntPtr hWnd, uint Msg, uint wParam, uint lParam);
// 宣告 DLL 中啟動訊息發送函式
[DllImport("MessageDLL.dll", EntryPoint = "StartSendMessage")]
private extern static void StartSendMessage(IntPtr hWnd);
protected override void OnPaint(PaintEventArgs e)
{
Font font = new Font("黑體", 28);
SolidBrush bluepen = new SolidBrush(Color.Blue);
SolidBrush blackpen = new SolidBrush(Color.FromArgb(0xa0, 0xa0, 0xb0));
e.Graphics.DrawString("VC知識庫", font, blackpen, 65, 25);
e.Graphics.DrawString("VC知識庫", font, bluepen, 61, 21); // 偏移 4 像素產生立體效果
}
// 測試應用程式訊息
private void TestAppbutton_Click(object sender, System.EventArgs e)
{
SendMessage(this.Handle, Message.WM_TEST, 100, 200);
}
// 測試 DLL 訊息
private void TestDLLbutton_Click(object sender, System.EventArgs e)
{
StartSendMessage(this.Handle);
}
protected override void DefWndProc(ref System.Windows.Forms.Message m)
{
string message;
switch (m.Msg)
{
case Message.WM_TEST:
message = string.Format("收到來自應用程式的訊息! 參數為: {0}, {1}", m.WParam, m.LParam);
MessageBox.Show(message);
break;
case Message.WM_MSG:
message = string.Format("收到來自 DLL 的訊息! 參數為: {0}, {1}", m.WParam, m.LParam);
MessageBox.Show(message);
break;
default:
base.DefWndProc(ref m); // 呼叫基類處理非自訂訊息
break;
}
}
DLL 端訊息定義請參考「VC.Net 從 DLL 傳遞訊息到 DLL」一文。