要让C# Winform窗口一直置顶显示在桌面的最上方或最底层需要使用其他的工具或API来实现。下面提供两种示例来解释如何实现这个功能。
方法一:使用Window API实现
可以通过调用Windows API来实现窗口置顶。具体步骤如下:
- 添加命名空间:
using System.Runtime.InteropServices;
using System.Text;
- 声明Windows API:
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
public const uint SWP_NOMOVE = 0x2;
public const uint SWP_NOSIZE = 0x1;
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
- 调用API:
将窗口置顶:
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
将窗口置底:
SetWindowPos(this.Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
方法二:使用TopMost属性实现
也可以通过直接设置窗口的TopMost属性,来让窗口置顶。具体步骤如下:
- 打开窗口的TopMost属性:
将窗口置顶:
this.TopMost = true;
将窗口置底:
this.TopMost = false;
- 在窗口关闭时,取消TopMost属性:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.TopMost = false;
//...
}
示例代码:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
public const uint SWP_NOMOVE = 0x2;
public const uint SWP_NOSIZE = 0x1;
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//将窗口置顶
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
private void button2_Click(object sender, EventArgs e)
{
//将窗口置底
SetWindowPos(this.Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//在窗口关闭时,取消TopMost属性
this.TopMost = false;
}
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:c# winform窗口一直置顶显示在桌面最上方或最底层的方法 - Python技术站