using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace DIYShutdown
{
static class Program
{
#region DllImportAttribute
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindow(string className, string windowText);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern bool ShowWindow(IntPtr handle, int flags);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern bool SetForegroundWindow(IntPtr handle);
#endregion
[STAThread]
static void Main()
{
#region Mutex
bool isCreated; // 互斥体名称须唯一。
using (Mutex newMutex = new Mutex(true, @"Local/DIYShutdown", out isCreated))
{
if (isCreated)
{
Application.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormShutdown());
newMutex.ReleaseMutex(); // 释放互斥体的所属权。
}
else
{
string text = string.Format("“{0}”应用程序已经运行。", AppDomain.CurrentDomain.FriendlyName);
MessageBox.Show(text, "系统提示!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
IntPtr handle = FindWindow("WindowsForms10.Window.8.app.0.378734a", "DIYShutdown");
if (handle != IntPtr.Zero)
{
ShowWindow(handle, 1);
SetForegroundWindow(handle);
}
}
}
#endregion
}
}
}
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
namespace DIYShutdown
{
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/DIYShutdown", out isCreated))
{
if (isCreated)
{
Application.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (RegistryKey subKey = Application.UserAppDataRegistry)
{
FormShutdown frame = new FormShutdown();
subKey.SetValue("Handle", frame.Handle);
Application.Run(frame);
}
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
}
}
}