如何在 C++ 中更改窗口大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21154060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change window size in C++?
提问by Ghanashyam Chakravarthi
Hi I have to run a program in C++ and I want to make sure when the program is executed, it opens the console in a particular size/dimensions, so that the display in my program is proper. I need help as I don't know how to do it. I am using Dev C++ 5.42(Orwell). I tried using
嗨,我必须用 C++ 运行一个程序,我想确保在执行该程序时,它会以特定的大小/尺寸打开控制台,以便我的程序中的显示正确。我需要帮助,因为我不知道该怎么做。我正在使用 Dev C++ 5.42(Orwell)。我尝试使用
#include<iostream>
#include<windows.h>
using namespace std;
SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
int main(){
cout<<"Hello World";
}
and got an error
并得到一个错误
[Error] expected constructor, destructor, or type conversion before '(' token
I'm a beginner and hence I don't know much about these things.
我是初学者,因此我对这些东西了解不多。
回答by Ben Voigt
That function is useless for console applications, which don't own a window (unless they create one using the CreateWindowAPI, which is atypical for console apps). Instead their output is connected to csrss, which does have windows.
该函数对于没有窗口的控制台应用程序是无用的(除非他们使用CreateWindowAPI创建一个窗口,这对于控制台应用程序来说是不典型的)。相反,它们的输出连接到具有窗口的 csrss。
You should be using
你应该使用
SetConsoleScreenBufferSizeSetConsoleWindowInfo
SetConsoleScreenBufferSizeSetConsoleWindowInfo
instead.
反而。
There's an example at http://www.cplusplus.com/forum/windows/10731/
回答by DaveWalley
This works for me:
这对我有用:
HWND hwnd = GetConsoleWindow();
if( hwnd != NULL ){ MoveWindow(hwnd ,340,550 ,680,150 ,TRUE); }
回答by Samarth S
If your looking for changing the screen buffer then :
如果您要更改屏幕缓冲区,则:
HANDLE buff = GetStdHandle(STD_OUTPUT_HANDLE);
COORD sizeOfBuff;
sizeOfBuff.X=150;
sizeOfBuff.Y=100;
SetConsoleScreenBufferSize(buff,sizeOfBuff);
To resize the screen use DaveWalley's solution.
要调整屏幕大小,请使用 DaveWalley 的解决方案。
Or you could do this (only for resizing)
或者你可以这样做(仅用于调整大小)
HWND hwnd = GetConsoleWindow();
if( hwnd != NULL ){ SetWindowPos(hwnd ,0,0,0 ,1000,300 ,SWP_SHOWWINDOW|SWP_NOMOVE); }
Be sure to include:
请务必包括:
#define _WIN32_WINNT 0x0502
#include<windows.h>
at the begining of the file. Literally as the first lines.
在文件的开头。字面意思是第一行。
Got the solution by reding about the functions mentioned by Ben Voigt.
通过 reding 关于 Ben Voigt 提到的功能得到了解决方案。

