using System;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace ProductManager
{
static class Program
{
#region DllImportAttribute
[DllImport("user32.dll", EntryPoint = "ShowWindow")]
static extern bool ShowWindow(IntPtr handle, int flags);
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
static extern bool SetForegroundWindow(IntPtr handle);
#endregion
[STAThread]
static void Main()
{
#region Mutex
bool isCreated; // 互斥体名称须唯一。
using (Mutex newMutex = new Mutex(true, @"Local\ProductManager", out isCreated))
{
if (isCreated)
{
Application.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("zh-CN");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormLogin());
newMutex.ReleaseMutex(); // 释放互斥体的所属权。
}
else
{
string text = string.Format("“{0}”应用程序已经运行。", AppDomain.CurrentDomain.FriendlyName);
MessageBox.Show(text, "系统提示!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
using (RegistryKey subKey = Application.UserAppDataRegistry)
{
IntPtr handle = new IntPtr(Convert.ToInt32(subKey.GetValue("Handle")));
ShowWindow(handle, 1);
SetForegroundWindow(handle);
}
}
}
#endregion
}
}
}
// FormLogin.cs
using System;
using System.Windows.Forms;
using Microsoft.Win32;
namespace ProductManager
{
public partial class FormLogin : Form
{
#region 自定义对象
private string title = "欢迎登录企业销售管理系统!";
#endregion
public FormLogin()
{
#region
InitializeComponent();
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.SizeGripStyle = SizeGripStyle.Hide;
this.FormBorderStyle = FormBorderStyle.Sizable;
this.StartPosition = FormStartPosition.CenterScreen;
this.AcceptButton = btnOK;
btnOK.DialogResult = DialogResult.OK; // 自定义有模式对话框确定按钮。
this.CancelButton = btnCancel; // 自定义有模式对话框取消按钮。
#endregion
}
#region FormLoad
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
txtID.Clear();
txtPwd.Clear();
}
#endregion
#region AcceptButton
private void btnOK_Click(object sender, EventArgs e)
{
if (ValidateUser)
{
txtID.Focus();
this.Hide();
using (RegistryKey subKey = Application.UserAppDataRegistry)
{
FormMain main = new FormMain();
subKey.SetValue("Handle", main.Handle);
main.Show();
}
}
else
{
MessageBox.Show(this, "您输入的用户名或密码有误, 请重新键入用户名和密码!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtPwd.Clear();
txtID.Focus();
txtID.SelectAll();
this.DialogResult = DialogResult.None; // 自定义有模式对话框继续运行
}
}
#endregion
#region CancelButton
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region timer_Tick
private void timer_Tick(object sender, EventArgs e)
{
if (this.Text.Length < title.Length)
this.Text = title.Substring(0, this.Text.Length + 1);
else
{
string str = this.Text.Trim();
this.Text = (str.Length > 0) ? this.Text.Replace(str[0], ' ') : null;
}
}
#endregion
}
}