如何设置一个控制台应用程序窗口为最上面的窗口(C#)?
问题描述:
我如何设置一个控制台应用程序是最上面的窗口。我建立在.NET控制台应用程序(我使用C#,甚至pinvokes非托管代码是确定)。
How do i set a console application to be the top most window. I am building the console application in .NET (i am using C# and maybe even pinvokes to unmanaged code is ok).
我以为我可以有我的控制台应用程序中获得从Form类
I thought that i could have my console application derive from Form class
class MyConsoleApp : Form {
public MyConsoleApp() {
this.TopLevel = true;
this.TopMost = true;
this.CenterToScreen();
}
public void DoSomething() {
//....
}
public static void Main() {
MyConsoleApp consoleApp = new MyConsoleApp();
consoleApp.DoSomething();
}
}
然而,这是行不通的。我不知道,如果Windows窗体上设置的属性适用于控制台UI。
However this doesn't work. I am not sure if the properties set on the windows form is applicable to the console UI.
答
您可以P / Invoke SetWindowPos
从Windows API:
You can P/Invoke SetWindowPos
from the Windows API:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(
IntPtr hWnd,
IntPtr hWndInsertAfter,
int x,
int y,
int cx,
int cy,
int uFlags);
private const int HWND_TOPMOST = -1;
private const int SWP_NOMOVE = 0x0002;
private const int SWP_NOSIZE = 0x0001;
static void Main(string[] args)
{
IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;
SetWindowPos(hWnd,
new IntPtr(HWND_TOPMOST),
0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE);
Console.ReadKey();
}
}