C#winform置顶不聚焦
时间: 2023-10-09 22:12:00 浏览: 106
C# Winform不规则窗体的实现
在C# WinForms中,要实现窗体置顶但不聚焦的效果,可以使用以下代码:
```csharp
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public partial class Form1 : Form
{
// 导入SetWindowPos函数
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
// 定义常量
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOMOVE = 0x0002;
private const uint SWP_NOACTIVATE = 0x0010;
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public Form1()
{
InitializeComponent();
}
protected override bool ShowWithoutActivation
{
get { return true; }
}
protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.ExStyle |= 0x08000000; // WS_EX_NOACTIVATE
return createParams;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// 窗体加载时设置置顶
SetTopMost(this.Handle);
}
private void SetTopMost(IntPtr handle)
{
SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
}
}
```
这段代码中,通过调用`SetWindowPos`函数,将窗体设置为置顶且不聚焦。在窗体加载时调用`SetTopMost`函数即可实现。
阅读全文