C#:窗体Topmost与获取输入焦点

仅设置 `TopMost = true` 无法保证窗体获取键盘输入焦点。需结合 Windows API `SetForegroundWindow` 强制激活窗口。

```csharp

using System;

using System.Runtime.InteropServices;

using System.Windows.Forms;

public partial class Form1 : Form

{

// 导入用户32库API

DllImport("user32.dll")

private static extern bool SetForegroundWindow(IntPtr hWnd);

DllImport("user32.dll")

private static extern IntPtr GetForegroundWindow();

public Form1()

{

InitializeComponent();

this.TopMost = true; // 设置置顶属性

}

/// <summary>

/// 调用此方法使窗体置顶并获取焦点

/// </summary>

public void ForceFocus()

{

// 如果窗口是最小化状态,需要先恢复

if (this.WindowState == FormWindowState.Minimized)

{

this.WindowState = FormWindowState.Normal;

}

// 尝试获取焦点

SetForegroundWindow(this.Handle);

// 可选:确保内部控件也获得焦点(如TextBox)

// this.ActiveControl?.Focus();

}

private void btnShow_Click(object sender, EventArgs e)

{

ForceFocus();

}

}

```

注意:

  1. Windows 安全机制限制后台进程随意抢占焦点。如果调用失败,通常是因为当前前台进程未授权。

  2. 若需持续保持焦点(如锁屏软件),需配合 `Timer` 周期性调用 `SetForegroundWindow` 并检查 `GetForegroundWindow()` 是否为本窗口句柄 。

  3. `TopMost` 仅控制 Z-order(显示层级),`SetForegroundWindow` 控制输入焦点,两者需配合使用 。

相关推荐
Warson_L1 分钟前
.NET 8 速成笔记 4:EF Core 迁移 (Migrations)
c#·.net
凌镜icecraft2 天前
我改文件扩展名的时候那个警告弹窗再也不会弹出来了
windows·c#·wpf·explorer
Jeff-Tsai2 天前
一个不用注册方法的 JSON-RPC 包,怎么决定哪些方法能被调用?
c#·.net·asp.net core·json-rpc
rockey6273 天前
AScript正式推出Template模板引擎
c#
沐言Agent3 天前
做工业上位机,这个 C# 开源框架把 PLC 通讯、流程控制和 MES 对接都备好了
c#·工业上位机
投研帮4 天前
C#文档管理系统开发实战:技术选型、全文检索与并发控制
c#·.net·文档管理系统
2395730494 天前
在 Avalonia 12 上用纯 .NET 重写 Monaco 编辑器:TKCode.Arc CodeEditor / DiffEditor / LSP 深度架构与实战
c#·.net·lsp·avalonia·monaco·codeeditor·tkcode.arc
新*5 天前
在 .NET 里嵌入 IronPython:内存只涨不降的真相与正确的封装姿势
c#·.net·内存优化·ironpython·dlr
2501_930707785 天前
使用C#从 PowerPoint 演示文稿中提取图片
开发语言·c#·powerpoint
zhanghaha13145 天前
C# 系列教程_15 类 Class 保姆级系统教程(面向新手,大量示例 + 底层机理)
java·开发语言·c#