动态关闭消息对话框

来源:互联网 发布:linux下安装samba 编辑:程序博客网 时间:2024/05/16 06:06

c#中用messagebox弹出对话框之后,点击确认或者取消  是或者否  之类的会自动关闭,但是有时候我们想动态关闭这个窗口该怎么做?或者是其他自定义弹框要动态关闭。方法有很多种,下面介绍几种。

1、调用Windows  API 获取消息弹窗的句柄,然后向消息窗口发送关闭或者取消 确定 消息。获取句柄的方法有多种,如果弹窗是模式对话框可以通过GetForegroundWindow得到当前活动的对话框句柄,如果是知道对话框的标题可以用FindWindow得到句柄

2、通过句柄利用SendMessage向窗体发送消息,或者利用ShowWindow关闭窗体,注意的是ShowWindow关闭窗体并不是真正的关闭的窗体,只是隐藏!还有CloseWindow也是一样的 并不是真正上的关闭窗体,真正的关闭窗体要用DestroyWindow


其他步骤还要导入 dll 什么的  见下面代码

 <span style="white-space:pre"></span>[DllImport("User32.dll")]        private static extern bool SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]        public static extern IntPtr GetForegroundWindow();        [DllImport("user32.dll", EntryPoint = "SetWindowText", CharSet = CharSet.Ansi)]        public static extern int SetWindowText(IntPtr hwnd, string lpString);        [DllImport("user32.dll", EntryPoint = "FindWindowA", CharSet = CharSet.Ansi)]        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

  <span style="white-space:pre"></span>private const int WM_Close = 0x0010;        private void button1_Click(object sender, EventArgs e)        {            timer1.Enabled = true;            MessageBox.Show(this, "ceshi", "提示", MessageBoxButtons.OkCancel, MessageBoxIcon.Question);                  }

   private void timer1_Tick(object sender, EventArgs e)        {            timer1.Enabled = false;      //      IntPtr myPtr = GetForegroundWindow();            IntPtr myPtr = FindWindow(null, "提示");             SetWindowText(myPtr, "TEST");            //SendKeys.Send("ENTER");            if (myPtr != IntPtr.Zero)            {                SendMessage(myPtr, WM_Close, IntPtr.Zero, IntPtr.Zero);            }                  }




0 0