C#控制台应用程序失去焦点

时间:2012-11-17 23:08:04

标签: c# windows scheduled-tasks console-application

我的本​​地PC上有大约15种不同的控制台应用程序,它们按照计划任务运行不同的时间段。

因为我将此电脑用作个人用途(例如在YouTube上观看或观看电影) 他们跳到我的屏幕上,但我必须总是手动将它们最小化。

我的目标是,我希望他们首先出现(已经在做)并在几秒钟后失去自动对焦。

Windows上是否可以使用控制台应用程序?

1 个答案:

答案 0 :(得分:3)

如果要最小化控制台窗口,可以使用WinApi

const Int32 SW_MINIMIZE = 6;

[DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern IntPtr GetConsoleWindow();

[DllImport("User32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow([In] IntPtr hWnd, [In] Int32 nCmdShow);

private static void MinimizeConsoleWindow()
{
    IntPtr hWndConsole = GetConsoleWindow();
    ShowWindow(hWndConsole, SW_MINIMIZE);
}

用法:

static void Main(string[] args)
{
    Console.WriteLine("Starting foo...");
    Thread.Sleep(1000); // hold console for a second on the screen
    MinimizeConsoleWindow();
    Console.ReadKey();
}