问题的解决
有时候实现一些自定义样式的窗体时,我们会将FormBorderStyle设置为None,这时候发现点击任务栏的窗口,窗口不会自己最小化了,其实给窗体重载一个属性可以解决这个问题
/// <summary> /// 重载该属性实现点击任务栏可以最小化窗体 /// </summary> protected override CreateParams CreateParams { get { const int MINIMIZEBOX = 0x00020000; CreateParams para = base.CreateParams; para.Style = para.Style | MINIMIZEBOX; return para; } }
实现原理
1、先上一段通过反编译System.Windows.Form.dll里面的代码,这段代码可以在Form类里面找到
protected override CreateParams CreateParams { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] get { CreateParams createParams = base.CreateParams; if (base.IsHandleCreated && ((base.WindowStyle & 0x8000000) != 0)) { createParams.Style |= 0x8000000; } else if (this.TopLevel) { createParams.Style &= -134217729; } if (this.TopLevel && (this.formState[FormStateLayered] != 0)) { createParams.ExStyle |= 0x80000; } IWin32Window window = (IWin32Window) base.Properties.GetObject(PropDialogOwner); if (window != null) { createParams.Parent = Control.GetSafeHandle(window); } this.FillInCreateParamsBorderStyles(createParams); this.FillInCreateParamsWindowState(createParams); this.FillInCreateParamsBorderIcons(createParams); if (this.formState[FormStateTaskBar] != 0) { createParams.ExStyle |= 0x40000; } FormBorderStyle formBorderStyle = this.FormBorderStyle; if (!this.ShowIcon && (((formBorderStyle == FormBorderStyle.Sizable) || (formBorderStyle == FormBorderStyle.Fixed3D)) || (formBorderStyle == FormBorderStyle.FixedSingle))) { createParams.ExStyle |= 1; } if (this.IsMdiChild) { if (base.Visible && ((this.WindowState == FormWindowState.Maximized) || (this.WindowState == FormWindowState.Normal))) { Form form = (Form) base.Properties.GetObject(PropFormMdiParent); Form activeMdiChildInternal = form.ActiveMdiChildInternal; if ((activeMdiChildInternal != null) && (activeMdiChildInternal.WindowState == FormWindowState.Maximized)) { createParams.Style |= 0x1000000; this.formState[FormStateWindowState] = 2; base.SetState(0x10000, true); } } if (this.formState[FormStateMdiChildMax] != 0) { createParams.Style |= 0x1000000; } createParams.ExStyle |= 0x40; } if (this.TopLevel || this.IsMdiChild) { this.FillInCreateParamsStartPosition(createParams); if ((createParams.Style & 0x10000000) != 0) { this.formState[FormStateShowWindowOnCreate] = 1; createParams.Style &= -268435457; } else { this.formState[FormStateShowWindowOnCreate] = 0; } } if (this.IsRestrictedWindow) { createParams.Caption = this.RestrictedWindowText(createParams.Caption); } if ((this.RightToLeft == RightToLeft.Yes) && this.RightToLeftLayout) { createParams.ExStyle |= 0x500000; createParams.ExStyle &= -28673; } return createParams; } }
可以看到,这里面窗体类通过重载这个属性,判断自身一些样式设置,返回一个参数,这个参数描述了窗体本身的很多样式信息。
显然如果在自己的窗体中重载这个属性,然后在基类原来实现的基础上,再增加一个允许最小化的属性,应该就能解决这个问题。
查手册找到最小化事件的数值为0x00020000,于是就有了刚开始的代码。