我创建了一个旨在运行单个实例的程序,其中包含一个隐藏的表单,直到收到广播消息。错误是除非在创建时显示表单,否则不会收到消息。为什么要在这个阶段展示表格?我举了一个例子。程序的第一个运行实例创建表单,其他实例向它广播消息。
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace HiddenProgram
{
public class Program : ApplicationContext
{
[DllImport("user32")]
static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
[DllImport("user32")]
static extern int RegisterWindowMessage(string message);
const int HWND_BROADCAST = 0xffff;
public static readonly int WM_SHOWME = Program.RegisterWindowMessage("com.holroyd.Gateway.Show");
public static Program Instance;
static Mutex mutex = new Mutex(true, "{9BFB3652-CCE9-42A2-8CDE-BBC40A0F5213}");
MyForm form;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (!mutex.WaitOne(TimeSpan.Zero, true))
{
// Show the single instance window
PostMessage(
(IntPtr)HWND_BROADCAST,
WM_SHOWME,
IntPtr.Zero,
IntPtr.Zero);
}
else
{
// Create the hidden window
Instance = new Program();
Application.Run(Instance);
mutex.ReleaseMutex();
}
}
Program()
{
form = new MyForm();
form.FormClosing += form_FormClosing;
// One of the following two seem necessary to get the broadcast message
form.Show();
//MainForm = form;
}
void form_FormClosing(object sender, FormClosingEventArgs e)
{
ExitThread();
}
}
public class MyForm : Form
{
protected override void WndProc(ref Message m)
{
if (m.Msg == Program.WM_SHOWME)
Visible = !Visible;
else
base.WndProc(ref m);
}
}
SMILET
相关分类