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` 控制输入焦点,两者需配合使用 。

相关推荐
波力海苔夹心脆6751 天前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
AI导出鸭PC端1 天前
Perplexity批量导出没有PDF模式?AI导出鸭插件补上最后一块拼图
人工智能·pdf·c#·ai导出鸭
Risehuxyc1 天前
C# 选用更流行的语言版本
c#
淡海水2 天前
09-04-内存-Unity原生对象生命周期
unity·c#·游戏引擎·gc
吴可可1232 天前
富怡CAD二次开发指南
c#
1-1=02 天前
C# IO和序列化
c#·.net·.netcore
寂寞的船2 天前
【Unity Bug挑战】第10期 SerializeReference 内存泄漏之谜
unity·c#·游戏引擎·bug
CSharp精选营2 天前
从控制台到「会动手」的 AI:用 Semantic Kernel 搭应用(小白教程)
c#·.net·ai agent·semantickernel·functioncalling
宝桥南山3 天前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore
1-1=03 天前
C# 中 Lambda、Linq 与 Expression
c#·linq