从任务栏隐藏应用程序时未收到 PostMessage
PostMessage not received when application is hidden from taskbar
如果另一个实例试图打开,我使用 PostMessage 向我的应用程序发送消息:
(CUSTOMTEXT
替换为我的应用名称)
NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_CUSTOMTEXT_SHOWME, IntPtr.Zero, IntPtr.Zero);
在 WndProc 中我收到消息:
protected override void WndProc(ref Message m)
{
if (m.Msg == NativeMethods.WM_CUSTOMTEXT_SHOWME)
{
MessageBox.Show("Message received");
}
base.WndProc(ref m);
}
和 NativeMethods class:
class NativeMethods
{
public const int HWND_BROADCAST = 0xffff;
public static readonly int WM_CUSTOMTEXT_SHOWME = RegisterWindowMessage("WM_CUSTOMTEXT_SHOWME");
[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.ShowInTaskbar = false;
) 隐藏我的应用程序时,我的应用程序停止接收该消息。
为什么?有什么解决方法吗?
找到替代解决方案:我将 PostMessage
(异步)替换为 SendMessage
(同步)。由于某种原因,SendMessage 可以通过而 PostMessage 没有。
在这个应用程序中,我使用哪个并不重要,因为当消息被发送时,应用程序就退出了。如果 Windows 处理这条消息只需要很少的时间,就没有坏处。重点是只有较旧的应用程序实例会收到此消息。
如果另一个实例试图打开,我使用 PostMessage 向我的应用程序发送消息:
(CUSTOMTEXT
替换为我的应用名称)
NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_CUSTOMTEXT_SHOWME, IntPtr.Zero, IntPtr.Zero);
在 WndProc 中我收到消息:
protected override void WndProc(ref Message m)
{
if (m.Msg == NativeMethods.WM_CUSTOMTEXT_SHOWME)
{
MessageBox.Show("Message received");
}
base.WndProc(ref m);
}
和 NativeMethods class:
class NativeMethods
{
public const int HWND_BROADCAST = 0xffff;
public static readonly int WM_CUSTOMTEXT_SHOWME = RegisterWindowMessage("WM_CUSTOMTEXT_SHOWME");
[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.ShowInTaskbar = false;
) 隐藏我的应用程序时,我的应用程序停止接收该消息。
为什么?有什么解决方法吗?
找到替代解决方案:我将 PostMessage
(异步)替换为 SendMessage
(同步)。由于某种原因,SendMessage 可以通过而 PostMessage 没有。
在这个应用程序中,我使用哪个并不重要,因为当消息被发送时,应用程序就退出了。如果 Windows 处理这条消息只需要很少的时间,就没有坏处。重点是只有较旧的应用程序实例会收到此消息。