我使用互斥锁来运行单个实例程序,现在我想让窗口在用户重新打开应用程序时最小化时最大化。
以下是我目前在Program.cs文件中的代码:
static class Program
{
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool Ok = true;
string ProductName = Application.ProductName;
Mutex m = new Mutex(true, ProductName, out Ok);
if (!Ok)
{
System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName(ProductName);
SetForegroundWindow(p[0].MainWindowHandle);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
答案 0 :(得分:7)
您正在寻找ShowWindow
function和SW_MAXIMIZE
标志。
在C#中,P / Invoke声明如下所示:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_MAXIMIZE = 3;
将此处添加到您的代码中:
if (!Ok)
{
Process[] p = Process.GetProcessesByName(ProductName);
SetForegroundWindow(p[0].MainWindowHandle);
ShowWindow(p[0].MainWindowHandle, SW_MAXIMIZE);
}
如果你真的想在最大化之前测试窗口是否被最小化,你可以使用旧学校IsIconic
function:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsIconic(IntPtr hWnd);
// [...]
if (!Ok)
{
Process[] p = Process.GetProcessesByName(ProductName);
IntPtr hwndMain= p[0].MainWindowHandle;
SetForegroundWindow(hwndMain);
if (IsIconic(hwndMain))
{
ShowWindow(hwndMain, SW_MAXIMIZE);
}
}
如果您只想激活窗口(而不是最大化窗口),请使用SW_SHOW
值(5
)代替SW_MAXIMIZE
。这将在最小化之前将其恢复到之前的状态。
答案 1 :(得分:2)
我想建议一个纯粹的.NET解决方案(即没有OS依赖)。
<强> Program.cs的强>
static class Program
{
private static volatile bool _exitProcess;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool createdNew;
var showMeEventHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "MyApp.ShowMe", out createdNew);
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form1();
new Thread(() =>
{
while (!_exitProcess)
{
showMeEventHandle.WaitOne(-1);
if (!_exitProcess)
{
if (form.InvokeRequired)
{
form.BeginInvoke((MethodInvoker)form.BringFormToFront);
}
else
{
form.BringFormToFront();
}
}
}
}).Start();
Application.Run(form);
}
_exitProcess = true;
showMeEventHandle.Set();
showMeEventHandle.Close();
}
}
<强> ExtMethods.cs 强>
public static class ExtMethods
{
public static void BringFormToFront(this Form form)
{
form.WindowState = FormWindowState.Normal;
form.ShowInTaskbar = true;
form.Show();
form.Activate();
}
}
<强> Form1.cs的强>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.BringFormToFront();
}
private void button1_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
ShowInTaskbar = false;
Hide();
}
}