Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a console application window to be the top most window (C#)?

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).

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();
    }
}

However this doesn't work. I am not sure if the properties set on the windows form is applicable to the console UI.

like image 929
Santhosh Avatar asked Jul 30 '10 08:07

Santhosh


1 Answers

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();
    }
}
like image 90
Dirk Vollmar Avatar answered Sep 21 '22 17:09

Dirk Vollmar