关于怎么在winform里增加登录窗体或者如何让winform程序单实例运行网上都很多例子。
然而两者结合起来呢?
//Program.cs
static class Program
{
public static EventWaitHandle ProgramStarted;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createNew;
ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, "MSFTD_SERVICE", out createNew);
if (!createNew)
{
ProgramStarted.Set();
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
try
{
LoginForm LoginForm = new LoginForm();
if (LoginForm.ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
}
catch (Exception ex)
{
//TODO
}
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//TODO
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
//TODO
}
}
//LoginForm.cs
public partial class LoginForm : Form
{
RegisteredWaitHandle handle;
public LoginForm()
{
InitializeComponent();
handle = ThreadPool.RegisterWaitForSingleObject(Program.ProgramStarted, OnProgramStarted, null, -1, false);
}
void OnProgramStarted(object state, bool timeout)
{
this.Invoke((MethodInvoker)delegate
{
this.Show();
this.WindowState = FormWindowState.Normal;
this.Activate();
});
} private void btn_Login_Click(object sender, EventArgs e)
{ handle.Unregister(null); this.DialogResult = DialogResult.OK; }
}
//MainForm.cs
public partial class MainForm : Form
{
#region init method, when user try to run two exe at the same time, show tips
public MainForm()
{
InitializeComponent();
this.SizeChanged += OnSizeChanged;
ThreadPool.RegisterWaitForSingleObject(Program.ProgramStarted, OnProgramStarted, null, -1, false);
this.WindowState = FormWindowState.Normal;
}
void OnSizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.notifyIcon.ShowBalloonTip(2000, "MSFTD Service", "MSFTD Service is running.", ToolTipIcon.Info);
this.Visible = false;
}
}
private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
}
void OnProgramStarted(object state, bool timeout)
{
this.Invoke((MethodInvoker)delegate
{
this.notifyIcon.ShowBalloonTip(2000, "MSFTD Service", "MSFTD Service is running.", ToolTipIcon.Info);
this.Show();
this.WindowState = FormWindowState.Normal;
this.Activate();
});
}
#endregion
}
来源:https://www.cnblogs.com/AlvinLiang/p/4976600.html