2010-07-30 72 views
8

如何將控制檯應用程序設置爲最頂層窗口。我正在.NET中構建控制檯應用程序(我正在使用C#,甚至可能會調用非託管代碼)。如何將控制檯應用程序窗口設置爲最頂層窗口(C#)?

我以爲我可以有我的控制檯應用程序從Form類

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。

回答

10

您可以P/Invoke SetWindowPos從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(); 
    } 
} 
+0

非常感謝!它很好用... – Santhosh 2010-07-30 09:47:06

0

你可以使用FindWindow用的P/Invoke(http://msdn.microsoft.com/en-us/library/ms633499(VS.85).aspx)然後以某種方式設置擴展的風格來使用WS_EX_TOPMOST - 見的P/Invoke SetWindowLonghttp://www.pinvoke.net/default.aspx/coredll/SetWindowLong.html)。

但是,這有點不好意思,建議使用Windows窗體或WPF創建自己的控制檯窗口。

+0

由於基倫。我如何使用Windows窗體創建控制檯窗口? – Santhosh 2010-07-30 09:22:10

+0

我想他正在試圖說,而不是寫一個控制檯應用程序,而是寫一個Windows窗體應用程序。 – user3454439 2015-02-04 09:41:55

相關問題