gpt4 book ai didi

c# - 使用 PInvoke 显示表单

转载 作者:太空宇宙 更新时间:2023-11-03 22:20:33 27 4
gpt4 key购买 nike

我有以下情况:WinForms 应用程序,它只允许运行此应用程序的一个实例(此处使用 Mutex 进行检查)。以某些 paramatere 开始的应用程序运行但隐藏。当有人再次点击应用程序时,Mutex 将检测到该应用程序已经在运行,并通过调用 native 方法“取消隐藏”主窗体(参见下面的方法 BringWindowToFront)。

下面是查找和显示窗体窗口的代码:

public static class NativeMethods
{
public enum ShowWindowOptions
{
FORCEMINIMIZE = 11,
HIDE = 0,
MAXIMIZE = 3,
MINIMIZE = 6,
RESTORE = 9,
SHOW = 5,
SHOWDEFAULT = 10,
SHOWMAXIMIZED = 3,
SHOWMINIMIZED = 2,
SHOWMINNOACTIVE = 7,
SHOWNA = 8,
SHOWNOACTIVATE = 4,
SHOWNORMAL = 1
}

[DllImport("user32.dll")]
public static extern int ShowWindow(int hwnd, int cmdShow);

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);

[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

public static void BringWindowToFront(string windowTitle)
{
// Get a handle to the application.
IntPtr handle = FindWindow(null, windowTitle);

// Verify that app is a running process.
if (handle == IntPtr.Zero)
{
return;
}

// With this line you have changed window status from example, minimized to normal
ShowWindow((int)handle, (int)ShowWindowOptions.SHOWDEFAULT);

// Make app the foreground application
SetForegroundWindow(handle);
}
}

一切都很好,但我还需要一个功能。当主窗体第一次取消隐藏时,我想显示另一个附加窗体。通常我通过 _Shown 事件来完成。但是当我使用 PInvoke 方法显示窗口时,这个事件没有被触发。

所以基本上我想在显示主窗体时显示附加窗体(使用 ShowWindow PInvoke 方法)

这可能吗?任何其他想法如何实现它?

最佳答案

编写单实例应用程序很棘手。您不必这样做,.NET 框架已经很好地支持它们。项目 + 添加引用,选择 Microsoft.VisualBasic。打开项目的 Program.cs 文件并使其看起来像这样:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic.ApplicationServices;

namespace WindowsFormsApplication1 {
class Program : WindowsFormsApplicationBase {
[STAThread]
static void Main(string[] args) {
var prg = new Program();
prg.EnableVisualStyles = true;
prg.IsSingleInstance = true;
prg.MainForm = new Form1();
prg.Run(args);
}

protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e) {
var main = this.MainForm as Form1;
main.WindowState = FormWindowState.Normal;
main.BringToFront();
// You could do something interesting with the command line arguments:
//foreach (var arg in e.CommandLine) {
// main.OpenFile(arg);
//}
}
}
}

关于c# - 使用 PInvoke 显示表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3241114/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com