September 7, 2008

Posting Windows Messages Accross Processes

public class WinMessagePoster
{
  [DllImport("user32")]
  public static extern bool PostMessage(IntPtr hwnd, int msg, 
          IntPtr wparam, IntPtr lparam);

  [DllImport("user32")]
  public static extern int RegisterWindowMessage(string message);

  // this class just wraps some Win32 stuffthat we're going to use
  public const int HWND_BROADCAST = 0xffff;

  public static readonly int WM_APP_MYMESSAGE = 
                                 RegisterWindowMessage("WM_APP_MYMESSAGE");

  public void PostWinMessageToAnotherApp()
  {
    Process[] processes = Process.GetProcessesByName("ApplicatioName");
    foreach (Process p in processes)
    {
      IntPtr pFoundWindow = p.MainWindowHandle;
      PostMessage(pFoundWindow, "WM_APP_MYMESSAGE", IntPtr.Zero, IntPtr.Zero);
    }
  }
}
In the application that receives the windows message
// In .exe Main Form
#region Detect Custom Windows Message

public static readonly int WM_APP_MYMESSAGE = 
  RegisterWindowMessage("WM_APP_MYMESSAGE");

[DllImport("user32")]
public static extern int RegisterWindowMessage(string message);

protected override void WndProc(ref Message m)
{
  if (m.Msg == WM_APP_MYMESSAGE)
  {
    DoSomething();
  }
  base.WndProc(ref m);
}

#endregion Detect Custom Windows Message

No comments: