zoukankan      html  css  js  c++  java
  • C#窗体MessageBox显示自动消失

    【说明】引自:http://xgli0910.blog.163.com/blog/static/4696216820127601455221/

    【前言】 MessageBox提示框一般需要手动关闭,对于简单的信息提示,每次还要去关闭很麻烦。于是想到怎样能让MessageBox显示一段时间后自动关闭。

    【代码】

     1 C#窗体MessageBox显示自动消失
     2 
     3 using System;
     4 using System.Collections.Generic;
     5 using System.Text;
     6 using System.Runtime.InteropServices;
     7 using System.Windows.Forms;
     8 
     9 namespace pdaTraceInfoPlat.beans
    10 {
    11     class MessageBoxTimeOut
    12     {
    13         private string _caption;
    14 
    15         public void Show(string text, string caption, int timeout)
    16         {
    17             this._caption = caption;
    18             StartTimer(timeout);
    19             MessageBox.Show(text, caption);
    20         }
    21 
    22         private void StartTimer(int interval)
    23         {
    24             Timer timer = new Timer();
    25             timer.Interval = interval;
    26             timer.Tick += new EventHandler(Timer_Tick);
    27             timer.Enabled = true;
    28         }
    29 
    30         private void Timer_Tick(object sender, EventArgs e)
    31         {
    32             KillMessageBox();
    33             //停止计时器
    34             ((Timer)sender).Enabled = false;
    35         }
    36 
    37         [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
    38         private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
    39 
    40         [DllImport("user32.dll", CharSet = CharSet.Auto)]
    41         public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
    42 
    43         public const int WM_CLOSE = 0x10;
    44 
    45         private void KillMessageBox()
    46         {
    47             //查找MessageBox的弹出窗口,注意对应标题
    48             IntPtr ptr = FindWindow(null, this._caption);
    49             if (ptr != IntPtr.Zero)
    50             {
    51                 //查找到窗口则关闭
    52                 PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
    53             }
    54         }       
    55     }
    56 }

    【注意】  windows系统中,DllImport应为user32.dll,即[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)],

    而不是   [DllImport("coredll.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]

  • 相关阅读:
    12.如何设置ulimit
    11.vim常用操作
    01Java jdk环境配置
    css
    Html
    day07 Class_field_method_反射
    JDBC
    Oracle day05 索引_数据去重
    Oracle day05 建表_约束
    Oracle day04 DML_事务_序列_视图_数据类型_DDL
  • 原文地址:https://www.cnblogs.com/denghuachengle/p/3521478.html
Copyright © 2011-2022 走看看