以下是一个示例代码,展示了如何保持Windows应用程序的活动状态,直到进程停止:
using System;
using System.Runtime.InteropServices;
class Program
{
// 导入Windows API函数
[DllImport("user32.dll")]
private static extern bool GetForegroundWindow();
[DllImport("kernel32.dll")]
private static extern IntPtr GetConsoleWindow();
static void Main(string[] args)
{
// 获取控制台窗口句柄
var consoleWindow = GetConsoleWindow();
// 检查进程是否处于活动状态
while (!Console.KeyAvailable && GetForegroundWindow() == consoleWindow)
{
// 进程处于活动状态时,执行你的代码
Console.WriteLine("应用程序正在运行...");
// 停顿一段时间
System.Threading.Thread.Sleep(1000);
}
// 当进程停止时,显示一条消息
Console.WriteLine("进程已停止...");
}
}
这个示例代码中,我们使用了GetForegroundWindow函数和GetConsoleWindow函数来检查进程是否处于活动状态。在Main方法中,我们使用一个循环来保持应用程序的活动状态,当控制台窗口失去焦点或用户按下任意键时,循环将停止。在循环中,你可以执行你的代码或任务。当进程停止时,会在控制台输出一条消息。