其實(shí)對于兩個(gè)程序之間進(jìn)行通信的實(shí)現(xiàn)方式有很多種,一般會(huì)采用服務(wù)端+客戶端的模式,此處我們是進(jìn)行兩個(gè)客戶端之間的通信,如果用一種最簡單的方式去實(shí)現(xiàn)的話,我認(rèn)為可以采用寫文件的方式,即一個(gè)讀,一個(gè)寫。這個(gè)寫法的話可以參考之前的關(guān)于文件讀寫的文章;
但這里我們使用的是另一種,基于Windows API實(shí)現(xiàn)Windows消息的發(fā)送接收;
實(shí)現(xiàn)功能:
開發(fā)環(huán)境:
開發(fā)工具:Visual Studio 2013
.NET Framework版本:4.5
實(shí)現(xiàn)代碼:
[DllImport("User32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(int hWnd, int msg, int wParam, ref COPYDATASTRUCT lParam);
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
const int WM_COPYDATA = 0x004A;
private void btnSend_Click(object sender, EventArgs e)
{
int hWnd = FindWindow(null, "客戶端2");
COPYDATASTRUCT cds;
cds.dwData = 0;
cds.cbData = System.Text.Encoding.Default.GetBytes(txtMsg.Text).Length + 1;
cds.lpData = txtMsg.Text;
SendMessage(hWnd, WM_COPYDATA, 0, ref cds);
}
public struct COPYDATASTRUCT
{
public int dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
const int WM_COPYDATA = 0x004A;
protected override void DefWndProc(ref System.Windows.Forms.Message m)
{
switch (m.Msg)
{
case WM_COPYDATA:
COPYDATASTRUCT myStr = new COPYDATASTRUCT();
Type myType = myStr.GetType();
myStr = (COPYDATASTRUCT)m.GetLParam(myType);
txtMsg.Text = myStr.lpData;
break;
default:
base.DefWndProc(ref m);
break;
}
}
public struct COPYDATASTRUCT
{
public int dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
實(shí)現(xiàn)效果:
這只是SendMessage諸多用法中的一個(gè),強(qiáng)大之處遠(yuǎn)不于此,后面會(huì)陸續(xù)寫出來。
該文章在 2023/2/27 10:53:37 編輯過