私はWinFormsアプリケーションを持っています。すでに&を実行しているインスタンスがある場合、別のインスタンスを起動しようとすると、Application.Run()を呼び出す前にMutexをチェックして停止します。その部分はうまく動作します。私がしたいのは、新しいプロセスを強制終了する前に、アプリケーションの新しいインスタンス(文字列形式のデータとともに)を既存のインスタンスに渡すことです。管理対象アプリのあるインスタンスから別のインスタンスにメッセージを送信するにはどうすればよいですか?
私はPostMessageを呼び出そうとしましたが、実行中のアプリケーションでメッセージを受け取りましたが、lparamで渡した文字列は失敗しています(はい、私は良い文字列を渡していることを確認しました〜から始まる)。どうすればこれを最もうまくできますか?私のフォーム内の別の場所
static class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool PostMessage(int hhwnd, uint msg, IntPtr wparam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint RegisterWindowMessage(string lpString);
private const int HWND_BROADCAST = 0xffff;
static uint _wmJLPC = unchecked((uint)-1);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
_wmJLPC = RegisterWindowMessage("JumpListProjectClicked");
if (_wmJLPC == 0)
{
throw new Exception(string.Format("Error registering window message: \"{0}\"", Marshal.GetLastWin32Error().ToString()));
}
bool onlyInstance = false;
Mutex mutex = new Mutex(true, "b73fd756-ac15-49c4-8a9a-45e1c2488599_ProjectTracker", out onlyInstance);
if (!onlyInstance) {
ProcessArguments();
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
GC.KeepAlive(mutex);
}
internal static void ProcessArguments()
{
if (Environment.GetCommandLineArgs().Length > 1)
{
IntPtr param = Marshal.StringToHGlobalAuto(Environment.GetCommandLineArgs()[1]);
PostMessage(HWND_BROADCAST, _wmJLPC, IntPtr.Zero, param);
}
}
}
、...
protected override void WndProc(ref Message m)
{
try
{
if (m.Msg == _wmJLPC)
{
// always returns an empty string
string param = Marshal.PtrToStringAnsi(m.LParam);
// UI code omitted
}
}
catch (Exception ex)
{
HandleException(ex);
}
base.WndProc(ref m);
}