【问题标题】:Maximizing console window - C#最大化控制台窗口 - C#
【发布时间】:2014-03-29 23:21:19
【问题描述】:

我正在使用 C# 开发控制台应用程序,我需要最大化打开控制台。当我只是点击控制台窗口上的最大化按钮时,它只在高度而不是宽度上最大化。我尝试使用以下代码:

   Console.WindowWidth = 150;
   Console.WindowHeight = 61;

这在我的计算机上几乎可以正常工作,但在其他一些计算机上会出错。 我应该怎么做才能最大化控制台?

【问题讨论】:

标签: c# .net visual-studio console console-application


【解决方案1】:

不能使用 CLR。需要导入 Win32 API 调用并戳你的容器窗口。以下可能会有所帮助。

using System.Diagnostics;
using System.Runtime.InteropServices;

[DllImport("user32.dll")]
public static extern bool ShowWindow(System.IntPtr hWnd, int cmdShow);

private static void Maximize()
{
    Process p = Process.GetCurrentProcess();
    ShowWindow(p.MainWindowHandle, 3); //SW_MAXIMIZE = 3
}

【讨论】:

  • 您能否更准确地说明如何使用此代码?
  • @user26830(假设代码可以满足您的需要)没有比这更简单的了
  • 我已经编辑了我的回复,为您提供可以剪切和粘贴的代码,并摆脱了 Visual Basic 的丑陋 :)
  • @JohnWu 谢谢,这好多了:)
  • 哇,我有Dan Appleman flashbacks。做得好;谢谢。
【解决方案2】:
    [DllImport("kernel32.dll", ExactSpelling = true)]

    private static extern IntPtr GetConsoleWindow();
    private static IntPtr ThisConsole = GetConsoleWindow();

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]

    private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    private const int HIDE = 0;
    private const int MAXIMIZE = 3;
    private const int MINIMIZE = 6;
    private const int RESTORE = 9;


    static void Main(string[] args)
    {
       ShowWindow(ThisConsole, MINIMIZE);
    }

【讨论】:

  • 请提供一些解释为什么代码可以解决问题。不鼓励仅使用代码回答。
  • 即使您在没有调试器的情况下启动控制台应用程序,此答案也有效,但接受的答案无效。另一个选项是 user32.dll 中的FindWindowByCaption
  • 我想应该是ShowWindow(ThisConsole, MAXIMIZE);
猜你喜欢
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
相关资源
最近更新 更多