此範例示範如何在兩個執行檔中使用SendMessage傳送值與接收值
此範例是傳遞int數字,如何傳遞string字串就給大家當做練習題了
以下這些程式碼是宣告會用到的API
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, UIntPtr
wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
uint MSG_SHOW = RegisterWindowMessage("Show Message");
[DllImport("user32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
IntPtr nPrt = FindWindow(null, "TestB");//找TestB的IntPtr 用來代表指標或控制代碼
http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=ZH-TW&k=k%28SYSTEM.INTPTR%29;k%28INTPTR%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV3.5%22%29;k%28DevLang-CSHARP%29&rd=true
SendMessage(nPrt, MSG_SHOW, iNum, IntPtr.Zero);
這行就是把數字傳送到目標視窗TestB
以下是TestA的完整程式碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TestA
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, UIntPtr
wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
uint MSG_SHOW = RegisterWindowMessage("Show Message");
[DllImport("user32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IntPtr nPrt = FindWindow(null, "TestB");//找TestB的IntPtr 用來代表指標或控制代碼
if (nPrt != IntPtr.Zero && textBox1.Text.Trim()!="" )
{
try
{
string tempWord = textBox1.Text.Trim();
int iNum = int.Parse(tempWord);//把tempWord字串 轉為int,所以值不是數字會變例外
SendMessage(nPrt, MSG_SHOW, iNum, IntPtr.Zero);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
以下是TestB的完整程式碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TestB
{
public partial class Form1 : Form
{
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
uint MSG_SHOW = RegisterWindowMessage("Show Message");
public Form1()
{
InitializeComponent();
}
protected override void WndProc(ref Message m)
{
if (m.Msg == MSG_SHOW)
{
label1.Text = (string) m.WParam.ToString();
}
base.WndProc(ref m);
}
}
}