How do I get the handle of a console application's window

前端 未结 6 1192
轻奢々
轻奢々 2020-11-27 18:56

Can someone tell me how to get the handle of a Windows console application in C#? In a Windows Forms application, I would normally try this.Handle.

6条回答
  •  被撕碎了的回忆
    2020-11-27 19:32

    I've just solved this problem for myself (unfortunately before seeing Thomas's answer which is much quicker). Well, here's another way for those who are not satisfied with his answer. I'm writing this answer because I want to provide another answer + a better way to design the Program class if you're treating your console as a Window. Let's begin with that design:

    I've kind of changed the default style of the Program class. I've actually made it into a class that has a program in it, and not just one method which represent it and uses other classes for content. (If you don't know what I mean, not important).

    The reason I had to do it is because I wanted to write the following event handler:

    private void CatchUnhandled(Object sender, UnhandledExceptionEventArgs e)
    {
        var exception = e.ExceptionObject as Exception;
        MessageBox.Show(this, exception.Message, "Error"); // Check out 1st arg.
    }
    

    It overloads this method MessageBox.Show(IWin32Window, String, String).

    Because Console doesn't implement IWin32Window, I had to implement it myself, of course, in order to just call this in the 1st argument.

    Here is the implementation of it and everything else:

    Note: this code is copy-pasted from my application, you can feel free to change the access modifiers

    Program Class Declaration:

    internal class Program : IWin32Window
    {
        ...
    }
    

    IWin32Window Implementation:

    public IntPtr Handle
    {
        get { return NativeMethods.GetConsoleWindow(); }
    }
    

    It uses the following class:

    internal static class NativeMethods
    {
        [DllImport("kernel32.dll")]
        internal static extern IntPtr GetConsoleWindow();
    }
    

    Now, the problem is that you can't actually call this in Main, being a static method, so whatever was in Main I've moved to a new method named Start and all Main is doing is creating a new Program and calling Start.

    private static void Main()
    {
        new Program().Start();
    }
    
    private void Start()
    {
        AppDomain.CurrentDomain.UnhandledException += CatchUnhandled;
    
        throw new Exception();
    }
    

    The result was, of course, a message-box with my console's window as an owner.
    Using this method for a message-box, is of course only one application of this method.

提交回复
热议问题