windows interprocess communication

For example with wpf

Receiving process code

1. Add the triggering event received

this.Title = "form name";

this.SourceInitialized += new EventHandler(win_SourceInitialized);

2. The receiving method

void win_SourceInitialized(object sender, EventArgs e)
{
HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
if (hwndSource != null)
{
hwndSource.AddHook(new HwndSourceHook(WndProc));
}
}

private const int WM_COPYDATA = 0x004A; // When an application sends this message to the data transfer when another application code can not modify fixed
protected Virtual IntPtr the WndProc (IntPtr HWND, int MSG, IntPtr the wParam, IntPtr the lParam, the Handled BOOL REF)
{
Switch (MSG)
{
Case WM_COPYDATA:
// your code
HandleCollector (HWND, the lParam);
the Handled = to true;
BREAK;
}
return IntPtr.Zero;
}

// WM_COPYDATA message data structures required by
public struct COPYDATASTRUCT
{
public IntPtr the dwData;
public int cbData;

[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}

private void HandleCollector(System.IntPtr hwnd, System.IntPtr lParam)
{
CopyDataStruct mmi = (CopyDataStruct)Marshal.PtrToStructure(lParam, typeof(CopyDataStruct));
if (mmi.lpData == "最大化")
{
this.ShowInTaskbar = true;
Show();
Activate();
this.WindowState = WindowState.Maximized;
}
}

 

The sender

// WM_COPYDATA message data structures required by
public struct COPYDATASTRUCT
{
public IntPtr the dwData;
public int cbData;

[MarshalAs(UnmanagedType.LPStr)]

public string lpData;
}

public const int WM_COPYDATA = 0x004A; // When an application sends the message to pass data to another application when the fixed code can not be modified

// to look through the window title of the window handle
[DllImport ( "User32.dll", EntryPoint = "FindWindow")]
Private static extern int FindWindow (lpClassName String, String lpWindowName);

// in the DLL library function sends a message
[the DllImport ( "the User32.dll", the EntryPoint = "the SendMessage")]
Private static extern int the SendMessage
(
int handle hWnd, // target window
int Msg, // here WM_COPYDATA
int wParam, // first message parameter
ref CopyDataStruct lParam // second message parameter
);

 

Send method of triggering

var msg = "maximize";
COPYDATASTRUCT CDS;
cds.dwData = (IntPtr). 1; // Here passed some custom data, but only 4 byte integer
cds.lpData = msg; // character message string
cds.cbData = System.Text.Encoding.Default.GetBytes (msg) .Length + 1; // note here is the length in bytes to count
SendMessage (FindWindow (null, "name form"), WM_COPYDATA , 0, ref cds);

Guess you like

Origin www.cnblogs.com/smalldragon-hyl/p/11911063.html