标签:protected state top test nta ptr rgs 程序 def
起源:
产品中,通常有些耗时操作比如转换等,在模态窗口中执行。此时最小化它,主窗体不能跟着最小化,影响操作。
如果让主窗体最小化,并且可以还原呢?搜索一番,未找到满意结果,自己动手吧!
1、改造Program.cs文件
其目的即以MainForm记录程序主窗体
static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); MainForm = new MainForm(); Application.Run(MainForm); } public static MainForm MainForm { get; set; } }
2、改写Modal窗体SizeChanged事件
在OnSizeChanged事件中处理FormWindowState.Minimized信号,最小化主窗体
public partial class TestForm : Form { [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("User32.dll")] public static extern int SetWindowPos(IntPtr hwnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, int wFlags); //ShowWindow参数 private const int SW_SHOWMINIMIZED = 2; private const int SWP_SHOWWINDOW = 0x40; public TestForm() { InitializeComponent(); this.ShowInTaskbar = false; } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); if (this.WindowState == FormWindowState.Minimized) { ShowWindow(Program.MainForm.Handle, SW_SHOWMINIMIZED); this.Visible = true; //移到屏幕外面,模拟最小化效果 SetWindowPos(this.Handle, IntPtr.Zero, Program.MainForm.Left, Program.MainForm.Top, 0, 0, SWP_SHOWWINDOW); //Trace.WriteLine(string.Format("x: {0}, y: {1}", Program.MainForm.Left, Program.MainForm.Top)); } } }
或直接用Owner,这样就不需第1步设置MainForm记录主窗体:
protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); if (this.WindowState == FormWindowState.Minimized) { var owner = this.Owner; if (owner != null) { ShowWindow(owner.Handle, SW_SHOWMINIMIZED); this.Visible = true; //移到屏幕外面,模拟最小化效果 SetWindowPos(this.Handle, IntPtr.Zero, owner.Left, owner.Top, 0, 0, SWP_SHOWWINDOW); //Trace.WriteLine(string.Format("x: {0}, y: {1}", Program.MainForm.Left, Program.MainForm.Top)); } } }
3、主窗体调用
using (var form = new TestForm()) { form.ShowDialog(this); }
显示效果如图:
标签:protected state top test nta ptr rgs 程序 def
原文地址:https://www.cnblogs.com/crwy/p/9707648.html