Declaring SMALL_RECT = {}, does not resize the console window - c++

I am just playing around with simple console applications in C++.
I am trying to resize the console window, and it works fine. First I resize the actual window, then the buffer and all is fine, but once I tried to compress the code, the window no longer resizes. It is really not that important. I am just generally wondering as most suggestions that I looked at declare the SMALL_RECT that way.
P.S I am using TDM-GCC 64 and Eclipse with std=c++17
This works and the window is resized properly
void SetCMDSizeAndTitle(short width, short height, string title) {
COORD coord = { width, height };
SMALL_RECT rect;
rect.Top = 0;
rect.Left = 0;
rect.Bottom = height - 1;
rect.Right = width - 1;
SetConsoleTitle(TEXT(title.c_str()));
SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &rect);
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
However this does not work, the window remains the default size
void SetCMDSizeAndTitle(short width, short height, string title) {
COORD coord = { width, height };
SMALL_RECT rect = { 0, 0, height - 1, width -1 };
SetConsoleTitle(TEXT(title.c_str()));
SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &rect);
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
This is not really that important. It is just nicer when there is less lines of code, and I am just generally curious why it doesn't work.

The reason it is not working is because according to the MSDN the variables are not in the order you assume. The MSDN defined the struct as
typedef struct _SMALL_RECT {
SHORT Left;
SHORT Top;
SHORT Right;
SHORT Bottom;
}
Which means you need to follow that order in the initialization list. That means you should have
SMALL_RECT rect = {0, 0, width -1, height - 1};
// L T R B

Related

Windows Console Resizing ignored - Screen buffer messed up

I'm going to ask the same question as countless people before me. I've tried about every solution out there but I seam to get the same output every time. I'm creating a console game engine and want to improve fps by using the windows API. However, Now that I have rotating polygons and such implemented, I'm realizing that the console resizes itself when the requested size extends about 100 x 100 characters. When this happens, the console gets resized to about 50 x 25 and the screen buffer shows absolute gibberish when I scroll to the right.
Here are some pictures:
I will supply just the relevant code for now but if anyone needs anymore I'd be glad to add it.
m_width = width;
m_height = height;
m_hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
m_hConsoleIn = GetStdHandle(STD_INPUT_HANDLE);
if (m_hConsole == INVALID_HANDLE_VALUE)
log += "Invalid std output console handle\n";
COORD bottemRight = { (signed)width, (signed)height };
if (!SetConsoleScreenBufferSize(m_hConsole, bottemRight))
log += "Error setting screen size\n";
m_screenBound = { 0, 0, (signed)width - 1, (signed)height - 1 };
if (!SetConsoleWindowInfo(m_hConsole, TRUE, &m_screenBound))
log += "Error initializing window info\n";
if (!SetConsoleActiveScreenBuffer(m_hConsole))
log += "Error setting active screen buffer\n";
I've also tried the HWND solution:
HWND hwnd = GetConsoleWindow();
RECT rect = { 0, 0, width, height };
MoveWindow(hwnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
I tried switching the window info setter and the screen buffer size setter and changed the window info rect to {0, 0, 1, 1} to no prevail. The output is pretty much exactly what you see in the pictures above.
Thanks in advance!
SOLVED
After noodling around with my code a bit, it turns out (based on the Microsoft documentation) that I need to something like this:
SMALL_RECT screen = { 0, 0, 1, 1 };
SetConsoleWindowInfo(m_handle, true, &screen);
COORD buffer_size = { width, height };
SetConsoleScreenBufferSize(m_handle, &buffer_size);
screen = { 0, 0, width - 1, height - 1 };
SetConsoleWindowInfo(m_handle, &screen);
This works for me now but thanks for your suggestions!

Can't center my console window by using the following code

void Initialize_Window(void)
{
RECT rConsole;
GetWindowRect(GetConsoleWindow(), &rConsole);
SetWindowPos(GetConsoleWindow(), NULL, 0, 0, 800, 700, 0);
SetWindowLong(GetConsoleWindow(), GWL_STYLE, GetWindowLong(GetConsoleWindow(), GWL_STYLE) & ~(WS_SIZEBOX | WS_MAXIMIZEBOX));
SetWindowPos(GetConsoleWindow(), NULL, (GetSystemMetrics(SM_CXSCREEN) - rConsole.right - rConsole.left) / 2, (GetSystemMetrics(SM_CYSCREEN) - rConsole.bottom - rConsole.top) / 2, 0, 0, SWP_NOSIZE);
}
I'm trying to center my console window by using the code above, but seems like the window just moved to a random position on my screen every time I execute the program, any idea how to fix it?
You need (GetSystemMetrics(SM_CXSCREEN) - (rConsole.right - rConsole.left))/2 to get center.
Side note: you can use one SetWindowPos instead of two (and do not need to get window Rect)
const int width = 800;
const int height = 700;
//SetWindowLong()...
SetWindowPos(GetConsoleWindow(), NULL,
GetSystemMetrics(SM_CXSCREEN)/2 - width/2,
GetSystemMetrics(SM_CYSCREEN)/2 - height/2,
width, height, SWP_SHOWWINDOW);
Don't use GetSystemMetrics() for this because it only returns the metrics of the primary monitor. Multi monitor setups are quite common these days so users will be rightly upset if you ignore that.
In addition, a window normally should not be aligned to the physical monitor surface, but to the work area which excludes the taskbar(s). Yes, there can be multiple taskbars (called "appbars" in Windows slang) on either side of the screen. An exception where you would actually use the full physical surface are full screen windows.
To cover both aspects we can use MonitorFromWindow() and GetMonitorInfo().
First we get the "nearest" monitor from the window handle. This is the monitor that either shows the window completely or that has the biggest area of the window on it:
HWND hConsoleWnd = ::GetConsoleWindow();
HMONITOR hMonitor = ::MonitorFromWindow( hConsoleWnd, MONITOR_DEFAULTTONEAREST );
Then we get the work area rectangle of that monitor and center the window relative to that:
if( hMonitor )
{
MONITORINFO info{ sizeof(info) }; // set cbSize member and fill the rest with zero
if( ::GetMonitorInfo( hMonitor, &info ) )
{
int width = 800;
int height = 700;
int x = ( info.rcWork.left + info.rcWork.right ) / 2 - width / 2;
int y = ( info.rcWork.top + info.rcWork.bottom ) / 2 - height / 2;
::SetWindowPos( hConsoleWnd, nullptr, x, y, width, height,
SWP_NOZORDER | SWP_NOOWNERZORDER );
}
}
That's it. In a real-world application you should of course not hardcode the window size because it is a user preference. For first launch a default size can be reasonable but even that should not be hardcoded but scaled according to the Windows DPI settings.

How to make background in MFC translucent?

I import a picture(.bmp or .jpeg) as the background of a client view in MFC.
When I click Open, function CDrawToolView::OnFileOpen() open a window to choose a picture, then I use ShowBitmap(CDC* pDC,CString strPicPath) and ShowPic(CDC* pDC,CString strPicPath) to load the picture as backgroud and adjust the size of client view to fit the picture.
I want to set the picture translucent, so the background looks softer. Could some one help me or give some suggestion, thanks.
Here is my code:
void CDrawToolView::ShowBitmap(CDC* pDC,CString strPicPath)
{
HBITMAP hBitmap=(HBITMAP)LoadImage(NULL,strPicPath,IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION|LR_DEFAULTSIZE|LR_LOADFROMFILE);
m_bitmap.Detach();
m_bitmap.Attach(hBitmap);
CRect rect;
GetClientRect(&rect);
CDC dcImage;
if (!dcImage.CreateCompatibleDC(pDC))
{
return;
}
BITMAP bm;
m_bitmap.GetBitmap(&bm);
dcImage.SelectObject(&m_bitmap);
pDC->StretchBlt(0,0,rect.right,rect.bottom,&dcImage,0,0,bm.bmWidth,bm.bmHeight,SRCCOPY);
}
void CDrawToolView::ShowPic(CDC* pDC,CString strPicPath)
{
if(!m_MyImage.IsNull())
m_MyImage.Destroy();
HRESULT hResult=m_MyImage.Load(strPicPath);
int iWidth=m_MyImage.GetWidth();
int iHeight=m_MyImage.GetHeight();
m_MyImage.Draw(pDC->m_hDC,0,0,iWidth,iHeight);
CRect client(0, 0, iWidth, iHeight);
client.bottom=client.bottom+::GetSystemMetrics(SM_CYMENU)+::GetSystemMetrics(SM_CYEDGE)*2;
client.right=client.right+::GetSystemMetrics(SM_CXEDGE)*2;
CFrameWnd* pFrame = GetParentFrame();
pFrame->CalcWindowRect(&client);
int width = client.Width();
int height = client.Height();
int y = (::GetSystemMetrics(SM_CYSCREEN) - height) / 2 + 100;
int x = (::GetSystemMetrics(SM_CXSCREEN) - width) / 2;
pFrame->SetWindowPos( NULL, x, y, width, height, SWP_NOACTIVATE | SWP_NOZORDER );
}
Use AlphaBlend instead of StretchBlt
CDC::AlphaBlend
Set SourceConstantAlpha in your BLENDFUNCTION struct to something like 128 (halfway between transparent and opaque), then adjust until it looks good.
AlphaFormat should be zero unless your usa a 32-bit bitmap with an alpha channel.

Win32 Screensaver multiple monitors with main display not leftmost

I've made a screensaver that simply scrolls user-defined text from right to left, automatically jumping back to the right if it exceeds the left boundary.
It works with multiple monitors flawlessly, barring one exception: if the 'Main Display' is on the right (i.e. Monitor #2 is primary), then I do not get the scrolling text, however the monitor IS blacked out by the code. If the main display is #1, there's no problem.
I've been poring over the code for hours and cannot identify at what stage the issue arises; I can confirm the text is in the right position (I inserted logging code that verifies its current position), but it's as if one of the API calls simply erases it. I've read the documentation for them and all looks ok.
I create a custom DC in WM_CREATE via:
if (( hDC = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL)) == NULL )
To prevent flicker, I create compatible objects to update:
void
TickerScreensaver::Paint_Prep(HDC hDC)
{
_devcon_mem = CreateCompatibleDC(hDC);
_devcon_orig = hDC;
_bmp_mem = CreateCompatibleBitmap(hDC, _width, _height);
}
and when painting in WM_PAINT (after BeginPaint, etc.), do a bit-block transfer to the actual device context:
void
TickerScreensaver::Paint(HDC hDC, RECT rect)
{
_bmp_orig = (HBITMAP)SelectObject(_devcon_mem, _bmp_mem);
FillRect(_devcon_mem, &rect, (HBRUSH)GetStockObject(BLACK_BRUSH));
if ( _gdiplus_token != NULL )
{
Graphics graphics(_devcon_mem);
SolidBrush brush(cfg.display.font_colour);
FontFamily font_family(cfg.display.font_family.c_str());
Font font(&font_family, cfg.display.font_size, FontStyleRegular, UnitPixel);
PointF point_f((f32)cfg.display.text_pos.x, (f32)cfg.display.text_pos.y);
RectF layout_rect(0, 0, 0, 0);
RectF bound_rect;
graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
graphics.MeasureString(cfg.display.text.c_str(), cfg.display.text.length(), &font, layout_rect, &bound_rect);
cfg.display.offset.x = (DWORD)(0 - bound_rect.Width);
cfg.display.offset.y = (DWORD)(bound_rect.Height / 2);
graphics.DrawString(cfg.display.text.c_str(), cfg.display.text.length(), &font, point_f, &brush);
}
BitBlt(hDC, 0, 0, _width, _height, _devcon_mem, 0, 0, SRCCOPY);
SelectObject(_devcon_mem, _bmp_orig);
}
I calculate the dimensions like so:
void
TickerScreensaver::GetFullscreenRect(HDC hDC, RECT *rect)
{
RECT s = { 0, 0, 0, 0 };
if ( EnumDisplayMonitors(hDC, NULL, EnumMonitorCallback, (LPARAM)&s) )
{
CopyRect(rect, &s);
s.left < 0 ?
_width = s.right + (0 + -s.left) :
_width = s.right;
s.top < 0 ?
_height = s.bottom + (0 + -s.top) :
_height = s.bottom;
}
}
Please note that the calculated width, height, etc., are all 100% accurate; it is purely the drawing code that doesn't appear to be working on the main display, only when it is on the right (which sets the origin to {0,0}, monitor #1 then being negative values). It is also reproduceable on a tri-display, with the main being in the center.
Well, turns out it is nice and simple - in Paint(), we should use a rect using the real width and height, not the one retrieved containing the negative values (the one actually retrieved from the API functions):
RECT r = { 0, 0, _width, _height };
_bmp_orig = (HBITMAP)SelectObject(_devcon_mem, _bmp_mem);
FillRect(_devcon_mem, &r, (HBRUSH)GetStockObject(BLACK_BRUSH));

MFC C++ Screenshot

I have an application that has drawn a grid using CDC (it has text, rectangle, and bitmaps). I want to take a screenshot of that finished grid when it is saved and use that screenshot as a "preview" for the file.
How can I take a screenshot of my application and save it?
Thank you,
Answer is here
void CScreenShotDlg::OnPaint()
{
// device context for painting
CPaintDC dc(this);
// Get the window handle of calculator application.
HWND hWnd = ::FindWindow( 0, _T( "Calculator" ));
// Take screenshot.
PrintWindow( hWnd,
dc.GetSafeHdc(),
0 );
}
Ultimately I ended up doing it this way because I wanted to capture even the hidden parts of the window (since the content extends beyond the screen and requires scrolling):
CDC* WindowToCaptureDC = AfxGetMainWnd()->GetWindowDC();
CDC CaptureDC;
CDC MemDC;
MemDC.CreateCompatibleDC(WindowToCaptureDC);
CaptureDC.CreateCompatibleDC(WindowToCaptureDC);
CBitmap CaptureBmp;
CBitmap ResizeBmp;
int pWidth = grid.tableWidth + grid.marginLeft*2;
int pHeight = grid.tableHeight + grid.marginBottom;
CaptureBmp.CreateCompatibleBitmap( WindowToCaptureDC, pWidth, pHeight);
CaptureDC.SelectObject(&CaptureBmp);
CBrush brush(RGB(255, 255, 255));
CaptureDC.SelectObject(&brush);
CaptureDC.Rectangle(0, 0, pWidth, pHeight);
///Drew items into CaptureDC like I did for OnDraw HERE///
double width = //desired width;
double height = //desired width;
//maintain aspect ratio
if(pWidth!=width || pHeight!=height)
{
double w = width/pWidth;
double h = height/pHeight;
if(w < h)
height = height*w;
else
width = width*h;
}
ResizeBmp.CreateCompatibleBitmap(WindowToCaptureDC, width, height);
MemDC.SelectObject(&ResizeBmp);
MemDC.StretchBlt(0, 0, width, height, &CaptureDC, 0, 0, pWidth, pHeight, SRCCOPY);
CImage TempImageObj;
TempImageObj.Attach((HBITMAP)ResizeBmp.Detach());
CString filePath = _T("LOCATION\\image.bmp");
TempImageObj.Save(filePath);