50 likes | 214 Views
系統之 DLL 引用與 PostMessage. 劉崇汎 崑山科技大學 電腦與通訊系 http://www.ksu.edu.tw. 系統的 DLL 調用與自制 DLL 不同. 引用System.Runtime.InteropServices using System.Runtime.InteropServices; 使用 C# 關鍵字 static 和 extern 聲明方法。使用DllImportAttribute 類別來使用API [DllImport( “ user32.dll ”)] // 紅色處可 替換成所需的DLL檔
E N D
系統之DLL引用與PostMessage 劉崇汎 崑山科技大學 電腦與通訊系 http://www.ksu.edu.tw
系統的DLL調用與自制DLL不同 • 引用System.Runtime.InteropServices • using System.Runtime.InteropServices; • 使用 C# 關鍵字 static 和 extern 聲明方法。使用DllImportAttribute 類別來使用API • [DllImport(“user32.dll”)] //紅色處可替換成所需的DLL檔 • 緊接著宣告extern的function定義 • public static extern ReturnTypeFunctionName(type arg1,type arg2,...); • 以上完成後就可以在程式中調用FunctionName所定義的函式
以PostMessage為例 • 建立兩個Window Form應用程式 • 第一個有一個Button作為Post • 第二個純接收message
PostMessageTest_Sender Using …………………… using System.Runtime.InteropServices; namespace PostMessageTest_Sender { public partial class Form1 : Form { [DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, UIntPtr wParam, IntPtr lParam); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern uint RegisterWindowMessage (string lpString); IntPtr HWND_BROADCAST = new IntPtr(0xffff); uint MSG_SHOW = RegisterWindowMessage("Show Message"); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { UIntPtr uPtr = new UIntPtr(100); SendMessage(HWND_BROADCAST, MSG_SHOW, uPtr, IntPtr.Zero); } } }
PostMessage_Receiver using ……………… using System.Runtime.InteropServices; namespace PostMessage_Receiver { public partial class Form1 : Form { [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern uint RegisterWindowMessage(string lpString); IntPtr HWND_BROADCAST = new IntPtr(0xffff); uint MSG_SHOW = RegisterWindowMessage("Show Message"); public Form1() { InitializeComponent(); } protected overridevoidWndProc(ref Message m) { if (m.Msg == MSG_SHOW) { MessageBox.Show("I get " + m.WParam.ToString()); } base.WndProc(ref m); } } }