窗体1中的代码:
/////////////////////////////////////////
///file name: Note.cs
///
public class Note
{
//声明 API 函数
[DllImport( "User32.dll", EntryPoint = "SendMessage" )]
private static extern int SendMessage(
int hWnd, // handle to destination window
int Msg, // message
int wParam, // first message parameter
int lParam // second message parameter
);
[DllImport( "User32.dll", EntryPoint = "FindWindow" )]
private static extern int FindWindow( string lpClassName, string lpWindowName );
//定义消息常数
public const int USER = 0x500;
public const int TEST = USER + 1;
//向窗体发送消息的函数
private void SendMsgToMainForm( int MSG )
{
int WINDOW_HANDLER = FindWindow( null, @"Note Pad" );
if( WINDOW_HANDLER == 0 )
{
throw new Exception( "Could not find Main window!" );
}
SendMessage( WINDOW_HANDLER, MSG, 100, 200 );
}
}
窗体2中的代码
/////////////////////////////////////////
/// File name : Form1.cs
/// 接收消息的窗体
///
public class Form1 : System.Windows.Forms.Form
{
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// 重写窗体的消息处理函数
protected override void DefWndProc( ref System.Windows.Forms.Message m )
{
switch( m.Msg )
{
//接收自定义消息 USER,并显示其参数
case Note.USER:
string message = string.Format( "Received message! parameters are :{0},{1}", m.WParam, m.LParam );
MessageBox.Show( message );
break;
default:
base.DefWndProc( ref m );
break;
}
//Console.WriteLine(m.LParam);
}
}