Closing all instances of an application

J

Jeremy Chapman

I start up several instances of an application I've written. From one of
the applications I'm trying to close all of them, but it's not working. I'm
doing this by registering a message and broadcasting it. but when I put a
breakpoint in my overridden WndProc, It never seems to get the message.

public class frmMyApplication : System.Windows.Forms.Form
{
public const int HWND_BROADCAST = 0xFFFF;

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int RegisterWindowMessage(string strMessageType);

[System.Runtime.InteropServices.DllImport(strUSER32DLL,
CharSet=CharSet.Auto, SetLastError=true)]
public static extern int SendMessage(IntPtr
hWnd,[MarshalAs(UnmanagedType.U4)] int iMsg, int iWParam, int iLParam);

int iCloseAllMessage_m;

public frmMyApplication()
{
iCloseAllMessage_m = MediScript.RegisterWindowMessage("_CloseMyApps");
if (iCloseAllMessage_m == 0)
{
throw new Exception("RegisterWindowMessage returned 0");
}
}

protected override void WndProc(ref Message m)
{
if (iCloseAllMessage_m != 0 && m.Msg == iCloseAllMessage_m)
{
Application.Exit();
}
else
{
base.WndProc (ref m);
}
}

private void mnuiCloseAll_Click(object sender, System.EventArgs e)
{
SendMessage((IntPtr)HWND_BROADCAST, iCloseAllMessage_m, 0,0);
}
}
 
G

Guest

I just tried it and it works for me. Are you using PInvoke to obtain
DllImport signatures? Below is the code:

//DllImports:

[DllImport("user32.dll")]
static extern System.IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr
wParam,
IntPtr lParam);


//Overload for string lParam (e.g. WM_GETTEXT)
[DllImport("user32.dll")]
static extern System.IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr
wParam,
[Out] System.Text.StringBuilder lParam);

[DllImport("user32.dll")]
static extern uint RegisterWindowMessage(string lpString);


//Registration code:
_messageId = Form1.RegisterWindowMessage("UNIQUE_CALL");
Form1.SendMessage(new IntPtr(HWND_BROADCAST), this._messageId, IntPtr.Zero,
IntPtr.Zero);
//note that _messageId returned is 49841

//Listening apps:
protected override void WndProc(ref Message m)
{
if (m.Msg == 49841)
{
Application.Exit();
}
else
{
base.WndProc (ref m);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top