怎么做到让程序窗口始终显示在桌面最上层,即始终掩盖在其他打开的窗口之上?(求C#实现代码)

如题所述

1、可以使用ShowDialog()。ShowDialog()将其置于程序最顶层,而且不能使用当前程序的其它窗体。

2、可以设置Form.TopMost 属性为true,关于此属性的介绍:

Form.TopMost 属性
获取或设置一个值,指示该窗体是否应显示为最顶层窗体。
命名空间:System.Windows.Forms
程序集:System.Windows.Forms(在 system.windows.forms.dll 中)

参考代码与注释:

private void CreateMyTopMostForm()
{
  // Create lower form to display.
  Form bottomForm = new Form();
  // Display the lower form Maximized to demonstrate effect of TopMost property.
  bottomForm.WindowState = FormWindowState.Maximized;
  // Display the bottom form.
  bottomForm.Show();
  // Create the top most form.
  Form topMostForm = new Form();
  // Set the size of the form larger than the default size.
  topMostForm.Size = new Size(300,300);
  // Set the position of the top most form to center of screen.
  topMostForm.StartPosition = FormStartPosition.CenterScreen;
  // Display the form as top most form.
  topMostForm.TopMost = true;
  topMostForm.Show();
}

两者二选一即可。 

温馨提示:内容为网友见解,仅供参考
第1个回答  2019-07-04

今天我尝试了一下,在窗体打开的时候开一个线程,然后这个线程里面一直设置TopMast=true就可以解决你的问题.

Thread mustTop = new Thread(() =>
            {
                while (!this.IsDisposed)//如果程序没有关闭,他就一直在上面.
                {
                    this.Invoke(new Action(() =>
                    {
                        this.TopMost = true;
                    }));
                    Thread.Sleep(1000);//可以隔一段时间设置一次
                }
            });
            mustTop.Start();

第2个回答  2013-04-11
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int Width, int Height, int flags);
/// <summary>
/// 得到当前活动的窗口
/// </summary>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern System.IntPtr GetForegroundWindow();
哪个窗体想要置顶,在Form_Load中加上
SetWindowPos(this.Handle, -1, 0, 0, 0, 0, 1 | 2); //最后参数也有用1 | 4 
具体说明,看API函数说明
如果是用点击一个按钮后弹出新窗体,并置顶,则:
Form2 frm = new Form2();
frm.Show();
SetWindowPos(GetForegroundWindow(), -1, 0, 0, 0, 0, 1 | 2);
这样,新打开的窗体就是置顶了。
第3个回答  2017-08-10
this.TopMost = true;
这样就可以了
第4个回答  2013-04-10
设置一个父窗体 看你是要显示子窗体还是父窗体咯
相似回答