起源:

产品中,通常有些耗时操作比如视频转换、DVD刻录等,在模态窗口中执行。此时最小化它,主窗体不能跟着最小化,影响操作体验。

如何让主窗体最小化,并且可以还原呢?搜索一番,未找到满意结果,自己动手吧!

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 = ;
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, , , SWP_SHOWWINDOW);
//Trace.WriteLine(string.Format("x: {0}, y: {1}", Program.MainForm.Left, Program.MainForm.Top));
}
}
}

或直接用Owner做控制。如果其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, , , 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);
}

显示效果如图:

c#: 模态窗口最小化主窗口-LMLPHP

05-11 22:26