I have a WPF application that is started with no parameters or flags. In the App.xaml.cs
I added an OnStartUp
handler that attempts to do some IPC to another instance of the application IF it executed with parameters. For example, my main application might be started by simply executing mainApp
, which would load the main windows. Then I might later execute mainApp msg bob some_message
which would pass the condition in OnStartUp
and send "msg bob some_message" to the up and running application to handle in its WndProc
override.
Code in App.xaml.cs:
private void OnStartUp(object sedner, StartupEventArgs e)
{
Process localProcess = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(localProcess.ProcessName))
{
if (process.Id != localProcess.Id)
{
NativeMethods.SendMessage(process.MainWindowHandle, NativeMethods.HWND_IPC, IntPtr.Zero, IntPtr.Zero);
Environment.Exit(0);
}
}
}
Code in main window codebehind:
public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr iParam, ref bool handled)
{
if (msg == NativeMethods.HWND_IPC)
{
MessageBox.Show("Message Received!");
}
return IntPtr.Zero;
}
internal class NativeMethods
{
public const int HWND_BROADCAST = 0xffff;
public const int HWND_IPC = 0xfffe;
public static readonly int WM_IPC = RegisterWindowMessage("WM_IPC");
public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
[DllImport("user32")]
public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
[DllImport("user32.dll")]//, CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessage(IntPtr hwnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32")]
public static extern int RegisterWindowMessage(string message);
}
I've tried this with many permutation of using PostMessage, SendMessage, just using static int messages, actually invoking the RegisterWindowMessage. Nothing seems to work.
Additionally, I would like to not just be able to specify a specific message, but also additional dynamic details like a username and some message text.