Winform 技巧

基本设置

热键响应

// Enter键响应按钮

this.AcceptButton = btnOK;

// ESC键响应按钮

this.CancelButton = btnOK;

居中

this.StartPosition = FormStartPosition.CenterScreen;

属性绑定

Winform 属性值绑定、转换、实时通知

子窗口

无模式窗口

dlg.Show(this);

无模式窗口,窗体的资源在窗体关闭时会自动释放(自动调用Close),因此 DialogResult 的值可能不是指定值。

模式对话框

dlg.ShowDialog(this);

if (dlg.DialogResult == DialogResult.OK)

{

// TODO

var value = dlg.PropertyName1;

}

dlg.Dispose();

当窗体显示为模式对话框时,关闭窗体不会自动调用Close。窗体只是处于隐藏状态,无需创建新的对话框实例即可再次显示。

在应用程序不再需要子窗体时,必须显式调用 Dispose。

窗体的返回值间接设置

按钮点击时返回给父窗口的值可以设置;

btnOK.DialogResult = DialogResult.OK;

按钮点击后,该窗体的DialogResult属性将设置为该按钮的DialogResult值。

取消标题栏

this.ControlBox = false;

this.Text = string.Empty;

弹框

蒙版弹框

其中,红色区域是用户控件。

this.ShowEditDialog(new DemoUserControl(), DialogClosedEventHandler);

private void DialogClosedEventHandler(object sender, ChildFormArgs e)

{

if (e.Result is DemoClass)

{

// TODO

}

}

this.ShowInfoDialog(new DemoUserControl());

窗体MaskChildForm 设计布局如下所示:

///

/// 弹框帮助类

///

public static class ChildFormHelper

{

///

/// 显示可编辑弹框

///

/// 父窗口

/// 对话框要显示的用户控件

/// 对话框关闭后回调

public static void ShowEditDialog(this Form parent, UserControl uc, EventHandler callback = null)

{

var child = uc as IUserControlResult;

if (child == null)

{

throw new Exception("UserControl must inherit from IUserControlResult");

}

else

{

var dlg = new MaskChildForm(parent.Location, parent.Size);

dlg.AddWithEdit(uc);

if (dlg.ShowDialog() == DialogResult.OK)

{

if (callback != null)

{

callback(null, new ChildFormArgs() { Result = child.CallbackResult });

}

}

dlg.Dispose();

}

}

///

/// 显示信息弹框

///

/// 父窗口

///

public static void ShowInfoDialog(this Form parent, UserControl uc)

{

var dlg = new MaskChildForm(parent.Location, parent.Size);

dlg.AddWithInfo(uc);

dlg.ShowDialog();

dlg.Dispose();

}

}

///

/// 弹框事件参数

///

public class ChildFormArgs : EventArgs

{

public object Result { get; set; }

}

///

/// 用户控件返回结果接口

///

interface IUserControlResult

{

///

/// 回调结果

///

object CallbackResult { get; set; }

}

子窗体可以是用户控件,必须继承IUserControlResult接口。

public partial class DemoUserControl : UserControl, IUserControlResult

{

public object CallbackResult { get; set; }

public DemoUserControl()

{

InitializeComponent();

}

protected override void OnHandleDestroyed(EventArgs e)

{

base.OnHandleDestroyed(e);

// 返回结果

CallbackResult = new DemoClass { P_String = DateTime.Now.ToString() };

}

}

licenses.licx

错误为“lc.exe已退出,代码为-1”。

解决方案:NuGet引用 EmptyLicensesLicx。

图像处理

刻度尺

具体实现见 自定义刻度尺

Loading

Winform 动态等待执行完成 Loading

Panel 滚动条

panelMain.AutoScroll = True;

// 需要滚动展示的子控件必须设置

ctrl.Anchor = Top;