目录
前言
在做机房的时候经常要对数据库的增删改查的操作进行提示,以方便我们知道操作是否成功,到目前为止,我们用到的基本都是MessageBox,但是这个提示也有缺点,当他弹出时,它的优先级最高,其他的就无法操作了,必须手动关闭才可以。为了解决这个问题,查了查资料,还真有不用手动关闭,自动就能关闭的操作,方法如下:
一、建类
1.ShowMsg类
将需要的一些参数封装成类,直接调用就可以,从这里也很好的体现了封装的好处。
public class ShowMsg
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string IpClassName, string IpWindowName);
[DllImport("user32.dll")]
static extern bool EndDialog(IntPtr hDlg, out IntPtr nResult);
//三个参数:1、文本提示-text,2、提示框标题-caption,3、按钮类型-MessageBoxButtons ,4、自动消失时间设置-timeout
public void ShowMessageBoxTimeout(string text, string caption,
MessageBoxButtons buttons, int timeout)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(CloseMessageBox),
new CloseState(caption, timeout));
MessageBox.Show(text, caption, buttons);
}
private static void CloseMessageBox(object state)
{
CloseState closeState = state as CloseState;
Thread.Sleep(closeState.Timeout);
IntPtr dlg = FindWindow(null, closeState.Caption);
if (dlg != IntPtr.Zero)
{
IntPtr result;
EndDialog(dlg, out result);
}
}
2.CloseState类
设置属性
public class CloseState
{
private int _Timeout;
public int Timeout
{
get
{
return _Timeout;
}
}
private string _Caption;
/// <summary>
/// Caption of dialog
/// </summary>
public string Caption
{
get
{
return _Caption;
}
}
public CloseState(string caption, int timeout)
{
_Timeout = timeout;
_Caption = caption;
}
}
二、调用方法
Model.ShowMsg show = new Model.ShowMsg();
show.ShowMessageBoxTimeout("下机成功!", "温馨提示", MessageBoxButtons.OK, 2000);
将建好的类实例化,直接调用提示框,并持续多长时间自动关闭,以上代码中持续时间的单位为ms。
扫描二维码关注公众号,回复:
9052485 查看本文章