用.NET写一个将指定窗口激活的函数,参数是进程的名字
时间: 2024-02-24 11:57:17 浏览: 24
好的,以下是一个用.NET编写的将指定进程的主窗口激活的函数:
```csharp
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
public class WindowActivator
{
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;
public static void ActivateWindowByProcessName(string processName)
{
Process[] processes = Process.GetProcessesByName(processName);
if (processes.Length > 0)
{
IntPtr hWnd = processes[0].MainWindowHandle;
if (IsIconic(hWnd))
{
ShowWindow(hWnd, SW_RESTORE);
}
SetForegroundWindow(hWnd);
}
}
}
```
这个函数使用了三个Win32 API,分别是`SetForegroundWindow`、`IsIconic`和`ShowWindow`。它们分别用于将指定窗口激活、判断窗口是否最小化、以及还原最小化的窗口。
你可以调用这个函数并传入要激活的进程的名称来实现将指定进程的主窗口激活的功能。如果有多个同名进程,则只激活第一个进程的主窗口。