I'm trying to stack some read-only textboxes on top of eachother to make a long scrollable list that can be cut and pasted.
So I create a simple textbox with a huge height....
HWND aTextBox=CreateWindow("Edit",theText.c(), WS_CHILD|WS_VISIBLE|ES_MULTILINE|ES_AUTOVSCROLL|ES_READONLY, 10, 10,aWidth-20,9999, aWindow, NULL, NULL, NULL);
SendMessage(aTextBox, WM_SETFONT, (WPARAM)gTextFont, 0);
...And now I want to figure out the height of the text within so that I can resize the textbox's height to fit.
I'm doing this right now:
HDC aHDC=GetDC(aTextBox);
RECT aRect;
DrawText(aHDC,theText.c(),theText.Len(),&aRect,DT_CALCRECT|DT_LEFT);
// Now size the textbox...
SetWindowPos(aTextBox,NULL,0,0,aWidth-20,aRect.bottom-aRect.top,SWP_NOMOVE);
I am getting strange results that seem to be close... but not exact. Some are too large, some are too small, some are spot on.
Anyone know what I'm doing wrong here?
Related
I have noticed that a text in the rich edit control (only a single line) is not centered vertically. A space between a text and a top border edge is larger than a space between a text and a botttom border edge. It is especially visible when a rich edit control height is only a little bit bigger that a text height. PARAMFORMAT only allow to set a horizontal alignment. How to set a vertical alignment / top-bottom margins ?
Edit:
This way I get PARAMFORMAT2 structure:
PARAFORMAT2 pf;
ZeroMemory(&pf, sizeof(pf));
pf.cbSize = sizeof(pf);
SendMessage(hwndRichEdit1, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
dySpaceBefore is already initially set to 0 and the effect you can see on the attached screenshot.
I use Visual Studio 2017, MSFTEDIT_CLASS is defined in Richedit.h as L"RICHEDIT50W"
If you're using a Rich Edit 2.0 control, you can use the PARAFORMAT2 structure, which has the option to set the space before the text.
You haven't added a language tag, but here's how you would do it in C (see also the documentation for EM_SETPARAFORMAT):
//...
PARAFORMAT2 pf2;
pf2.cbSize = sizeof(PARAFORMAT2);
pf2.dwMask = PFM_SPACEBEFORE; // Of course, you can OR in other bits/options to set!
pf2.dySpaceBefore = 0; // Will align to the top; use a small +ve value, if you prefer
SendMessage(hWndEdit, EM_SETPARAFORMAT, 0, (LPARAM)&pf2);
//...
To get vertically centred text is bit more work, as you will need to get the height of the text (using GetTextExtent) and the height of the control's client rectangle, then use a 'space before' value of (client_height - text_height)/2.
Feel free to ask for further clarification and/or explanation. (I may even be able to offer you code in another language.)
I can reproduce this issue like this snapshot shows:
There seems no feature supported for vertical alignment center. I've submit a feature request internally.
A workaround is using EM_SETRECT which can move up text area via limiting rectangle into which the control draws the text. The following snapshots show its effects:
Then you can use it to adjust the text to display it in center between top and bottom.
Code example:
HWND hwndEdit = CreateWindowEx(
0,
MSFTEDIT_CLASS,
TEXT("EDIT"),
WS_BORDER | WS_VISIBLE | WS_CHILD,
20,
20,
100,
32,
hWnd,
NULL,
hInst,
NULL);
RECT rect;
SendMessage(hwndEdit, EM_GETRECT, 0, (LPARAM)&rect);
rect.top -= 2;
rect.bottom -= 2;
SendMessage(hwndEdit, EM_SETRECT, 1, (LPARAM)&rect);
I'm working on an app that positions windows on the screen in a grid style. When Running this on Windows 10, there is a huge gap between the windows. Further investigation shows that GetWindowRect is returning unexpected values, including an invisible border, but I can't get it to return the real values with the visible border.
1) This thread suggests this is by design and you can "fix" it by linking with winver=6. My environment does not allow this but I've tried changing the PE MajorOperatingSystemVersion and MajorSubsystemVersion to 6 with no affect
2) That same thread also suggests using DwmGetWindowAttribute with DWMWA_EXTENDED_FRAME_BOUNDS to get the real coordinates from DWM, which works, but means changing everywhere that gets the window coordinates. It also doesn't allow the value to be set, leaving us to reverse the process to be able to set the window size.
3) This question suggests it's lack of the DPI awareness in the process. Neither setting the DPI awareness flag in the manifest, or calling SetProcessDpiAwareness had any result.
4) On a whim, I've also tried adding the Windows Vista, 7, 8, 8.1 and 10 compatibility flags, and the Windows themes manifest with no change.
This window is moved to 0x0, 1280x1024, supposedly to fill the entire screen, and when querying the coordinates back, we get the same values.
The window however is actually 14 pixels narrower, to take into account the border on older versions of Windows.
How can I convince Windows to let me work with the real window coordinates?
Windows 10 has thin invisible borders on left, right, and bottom, it is used to grip the mouse for resizing. The borders might look like this: 7,0,7,7 (left, top, right, bottom)
When you call SetWindowPos to put the window at this coordinates:
0, 0, 1280, 1024
The window will pick those exact coordinates, and GetWindowRect will return the same coordinates. But visually, the window appears to be here:
7, 0, 1273, 1017
You can fool the window and tell it to go here instead:
-7, 0, 1287, 1031
To do that, we get Windows 10 border thickness:
RECT rect, frame;
GetWindowRect(hwnd, &rect);
DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, &frame, sizeof(RECT));
//rect should be `0, 0, 1280, 1024`
//frame should be `7, 0, 1273, 1017`
RECT border;
border.left = frame.left - rect.left;
border.top = frame.top - rect.top;
border.right = rect.right - frame.right;
border.bottom = rect.bottom - frame.bottom;
//border should be `7, 0, 7, 7`
Then offset the rectangle like so:
rect.left -= border.left;
rect.top -= border.top;
rect.right += border.left + border.right;
rect.bottom += border.top + border.bottom;
//new rect should be `-7, 0, 1287, 1031`
Unless there is a simpler solution!
How can I convince Windows to let me work with the real window coordinates?
You are already working with the real coordinates. Windows10 has simply chosen to hide the borders from your eyes. But nonetheless they are still there. Mousing past the edges of the window, your cursor will change to the resizing cursor, meaning that its still actually over the window.
If you want your eyes to match what Windows is telling you, you could try exposing those borders so that they are visible again, using the Aero Lite theme:
http://winaero.com/blog/enable-the-hidden-aero-lite-theme-in-windows-10/
AdjustWindowRectEx (or on Windows 10 and later AdjustWindowRectExForDpi) might be of use. These functions will convert a client rectangle into a window size.
I'm guessing you don't want to overlap the borders though, so this probably isn't a full solution--but it may be part of the solution and may be useful to other people coming across this question.
Here's a quick snippet from my codebase where I've successfully used these to set the window size to get a desired client size, pardon the error handling macros:
DWORD window_style = (DWORD)GetWindowLong(global_context->window, GWL_STYLE);
CHECK_CODE(window_style);
CHECK(window_style != WS_OVERLAPPED); // Required by AdjustWindowRectEx
DWORD window_style_ex = (DWORD)GetWindowLong(global_context->window, GWL_EXSTYLE);
CHECK_CODE(window_style_ex);
// XXX: Use DPI aware version?
RECT requested_size = {};
requested_size.right = width;
requested_size.bottom = height;
AdjustWindowRectEx(
&requested_size,
window_style,
false, // XXX: Why always false here?
window_style_ex
);
UINT set_window_pos_flags = SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER;
CHECK_CODE(SetWindowPos(
global_context->window,
nullptr,
0,
0,
requested_size.right - requested_size.left,
requested_size.bottom - requested_size.top,
set_window_pos_flags
));
There are still two ambiguities in the above use case:
My window does have a menu, but I have to pass in false for the menu param or I get the wrong size out. I'll update this answer with an explanation if I figure out why this is!
I haven't yet read about how Windows handles DPI awareness so I'm not sure when you want to use that function vs the non DPI aware one
You can respond to the WM_NCCALCSIZE message, modify WndProc's default behaviour to remove the invisible border.
As this document and this document explain, when wParam > 0, On request wParam.Rgrc[0] contains the new coordinates of the window and when the procedure returns, Response wParam.Rgrc[0] contains the coordinates of the new client rectangle.
The golang code sample:
case win.WM_NCCALCSIZE:
log.Println("----------------- WM_NCCALCSIZE:", wParam, lParam)
if wParam > 0 {
params := (*win.NCCALCSIZE_PARAMS)(unsafe.Pointer(lParam))
params.Rgrc[0].Top = params.Rgrc[2].Top
params.Rgrc[0].Left = params.Rgrc[0].Left + 1
params.Rgrc[0].Bottom = params.Rgrc[0].Bottom - 1
params.Rgrc[0].Right = params.Rgrc[0].Right - 1
return 0x0300
}
I am using my own tooltip to display quick help about a currently selected item in my autocomplete listbox used in my editor. Just like VS does it for source code editor, when a new selection happens, the tooltip permanently and immediately pops up next to the current selection, and remains there until new selection of autocomplete listbox is gone.
This is a WTL project if that matters.
The way I create amd display my tooltip:
m_hwndTooltip = CreateWindowEx(WS_EX_TOPMOST,
TOOLTIPS_CLASS,
NULL,
TTS_NOPREFIX | TTS_ALWAYSTIP,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
NULL,
NULL
);
// INITIALIZE MEMBERS OF THE TOOLINFO STRUCTURE
m_toolTipInfo.cbSize = TTTOOLINFOA_V2_SIZE;
m_toolTipInfo.uFlags = TTF_TRACK;
m_toolTipInfo.hwnd = NULL;
m_toolTipInfo.hinst = NULL;
m_toolTipInfo.uId = 0; // ??
m_toolTipInfo.lpszText = (LPTSTR) messsssssssage.c_str();
// Tool_tip control will cover the whole window
m_toolTipInfo.rect.left = 0;
m_toolTipInfo.rect.top = 0;
m_toolTipInfo.rect.right = 0;
m_toolTipInfo.rect.bottom = 0;
::SendMessage(m_hwndTooltip, TTM_SETMAXTIPWIDTH, 0, MAX_TOOLTIP_WIDTH); //set max width in pixels, AND(!!) enable multi-line support
// SEND AN ADDTOOL MESSAGE TO THE TOOLTIP CONTROL WINDOW
::SendMessage(m_hwndTooltip, TTM_ADDTOOL, 0, (LPARAM) (LPTOOLINFO) &m_toolTipInfo);
::SendMessage(m_hwndTooltip, TTM_TRACKPOSITION, 0, (LPARAM)(DWORD) MAKELONG(x, y));
::SendMessage(m_hwndTooltip, TTM_TRACKACTIVATE, true, (LPARAM)(LPTOOLINFO) &m_toolTipInfo);
This is all fine, works like a charm.
However, when I pass too high Y coord which would make tooltip out of the screen on the bottom side (eg: Screen height: 1000, and I pass Y: 950, and tooltip will be 100 height), then the Tooltip appears on the Y=0, so the screen top position, instead of repositioning to 900.
However, this works horizontally, so if it would be out on the right side (so too high X is passed), it moves left the Tooltip until it can fit on the screen.
This is very strange and weird?!
Can anyone give me a tip what is the problem here?
Not to mention, the Tooltip size is determined by the win tooltip automatically, based on the message to display + max width + font used + line numbers, so I cannot calculate a correct X,Y position before displaying it, so I need to rely on the Tooltip control.
As no reply, and I found the solution, I will share it for others:
It seems the initially 0,0 is a kind of fallback when tooltip fails to fit on the screen.
So what I do, instead of
m_toolTipInfo.rect.top = 0;
m_toolTipInfo.rect.buttom = 0;
--->
m_toolTipInfo.rect.top = rcWorkingArea.bottom - 5;
m_toolTipInfo.rect.bottom = rcWorkingArea.bottom - 5;
If tooltip cannot fit on the screen bottom side, this value will be used.
Still strange why does it work automatically with X coord...but never mind.
We are seeing an intermittent problem in which owner drawn buttons under Windows XP that are using a bitmap as a backdrop are displaying the bitmap incorrectly. The window containing multiple buttons that are using the same bitmap file for the bitmap image used for the button backdrop will display and most of the buttons will be correct though in some cases there may be one or two buttons which are displaying the bitmap backdrop reduced to a smaller size.
If you exit the application and then restart it you may see the same behavior of the incorrect display of the icon on the buttons however it may or may not be the same buttons as previously. Nor is this behavior of incorrect display of icons on the buttons always seen. Sometimes it shows and sometimes it does not. Since once we load an icon for a button we just keep it, once the button is displayed incorrectly it will always be displayed incorrectly.
Using the debugger we have finally found that what appears to be happening is that when the GetObject() function is called, the data returned for the bitmap size is sometimes incorrect. For instance in one case the bitmap was 75x75 pixels and the size returned by GetObject() was 13x13 instead. Since this size is used as part of the drawing of the bitmap, the displayed backdrop becomes a small decoration on the button window.
The actual source area is as follows.
if (!hBitmapFocus) {
CString iconPath;
iconPath.Format(ICON_FILES_DIR_FORMAT, m_Icon);
hBitmapFocus = (HBITMAP)LoadImage(NULL, iconPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
}
if (hBitmapFocus) {
BITMAP bitmap;
int iNoBytes = GetObject(hBitmapFocus, sizeof(BITMAP), &bitmap);
if (iNoBytes < 1) {
char xBuff[128];
sprintf (xBuff, "GetObject() failed. GetLastError = %d", GetLastError ());
NHPOS_ASSERT_TEXT((iNoBytes > 0), xBuff);
}
cxSource = bitmap.bmWidth;
cySource = bitmap.bmHeight;
//Bitmaps cannot be drawn directly to the screen so a
//compatible memory DC is created to draw to, then the image is
//transfered to the screen
CDC hdcMem;
hdcMem.CreateCompatibleDC(pDC);
HGDIOBJ hpOldObject = hdcMem.SelectObject(hBitmapFocus);
int xPos;
int yPos;
//The Horizontal and Vertical Alignment
//For Images
//Are set in the Layout Manager
//the proper attribute will have to be checked against
//for now the Image is centered on the button
//Horizontal Alignment
if(btnAttributes.horIconAlignment == IconAlignmentHLeft){//Image to left
xPos = 2;
}else if(btnAttributes.horIconAlignment == IconAlignmentHRight){//Image to right
xPos = myRect.right - cxSource - 5;
}else {//Horizontal center
xPos = ((myRect.right - cxSource) / 2) - 1;
}
//Vertical Alignment
if(btnAttributes.vertIconAlignment == IconAlignmentVTop){//Image to top
yPos = 2;
}else if(btnAttributes.vertIconAlignment == IconAlignmentVBottom){//Image to bottom
yPos = myRect.bottom - cySource - 5;
}else{//Vertical Center
yPos = ((myRect.bottom - cySource) / 2) - 1;
}
pDC->BitBlt(xPos, yPos, cxSource, cySource, &hdcMem, 0, 0, SRCCOPY);
hdcMem.SelectObject(hpOldObject);
}
Using the debugger we can see that the iconPath string is correct and the bitmap is loaded as hBitmapFocus is not NULL. Next we can see that the call to GetObject() is made and the value returned for iNoBytes equals 24. For those buttons that display correctly the values in bitmap.bmWidth and bitmap.bmHeight are correct however for those that do not the values are much too small leading to an incorrect sizing when drawing the bitmap.
The variable is defined in the class header as
HBITMAP hBitmapFocus;
As part of doing the research for this I found this stack overflow question, GetObject returns strange size and I am wondering if there is some kind of an alignment issue here.
Does the bitmap variable used in the call to GetObject() need to be on some kind of an alignment boundary? While we are using packed for some of our data we are using pragma directives to only specify specific portions of code containing specific structs in include files that need to be packed on one byte boundaries.
Please read this Microsoft KB how to load a bitmap with palette information. It has a great example as well.
On the side note: I do not see anywhere in your code where you call ::DeleteObject(hBitmapFocus). It is very important to call this, as you can run out of GDI objects very quickly.
It is always a good idea to use Windows Task manager to see that your program does not exhaust the GDI resources. Just add "GDI Objects" column to the Task Manager and see that the number of objects is not constantly increasing in your app, but stays within an expected range, similar to other programs
I'm drawing old school (unthemed - themed radios are a whole other problem) radio buttons myself using DrawFrameControl:
DrawFrameControl(dc, &rectRadio, DFC_BUTTON, isChecked() ? DFCS_BUTTONRADIO | DFCS_CHECKED : DFCS_BUTTONRADIO);
I've never been able to figure out a sure fire way to figure out what to pass for the RECT. I've been using a 12x12 rectangle but I'de like Windows to tell me the size of a radio button.
DrawFrameControl seems to scale the radio button to fit the rect I pass so I have to be close to the "right" size of the radio looks off from other (non-owner drawn) radios on the screen.
Anyone know how to do this?
This page shows some sizing guidelines for controls. Note that the sizes are given in both DLU (dialog units) and pixels, depending on whether you are placing the control on a dialog or not:
http://msdn.microsoft.com/en-us/library/aa511279.aspx#controlsizing
I thought the GetSystemMetrics API might return the standard size for some of the common controls, but I didn't find anything. There might be a common control specific API to determine sizing.
It has been a while since I worked on this, so what I am describing is what I did, and not necessarily a direct answer to the question.
I happen to use bit maps 13 x 13 rather than 12 x 12. The bitmap part of the check box seems to be passed in the WM_DRAWITEM. However, I had also set up WM_MEASUREITEM and fed it the same values, so my answer may well be "Begging the question" in the correct philosophical sense.
case WM_MEASUREITEM:
lpmis = (LPMEASUREITEMSTRUCT) lParam;
lpmis->itemHeight = 13;
lpmis->itemWidth = 13;
break;
case WM_DRAWITEM:
lpdis = (LPDRAWITEMSTRUCT) lParam;
hdcMem = CreateCompatibleDC(lpdis->hDC);
if (lpdis->itemState & ODS_CHECKED) // if selected
{
SelectObject(hdcMem, hbmChecked);
}
else
{
if (lpdis->itemState & ODS_GRAYED)
{
SelectObject(hdcMem, hbmDefault);
}
else
{
SelectObject(hdcMem, hbmUnChecked);
}
}
StretchBlt(
lpdis->hDC, // destination DC
lpdis->rcItem.left, // x upper left
lpdis->rcItem.top, // y upper left
// The next two lines specify the width and
// height.
lpdis->rcItem.right - lpdis->rcItem.left,
lpdis->rcItem.bottom - lpdis->rcItem.top,
hdcMem, // source device context
0, 0, // x and y upper left
13, // source bitmap width
13, // source bitmap height
SRCCOPY); // raster operation
DeleteDC(hdcMem);
return TRUE;
This seems to work well for both Win2000 and XP, though I have nbo idea what Vista might do.
It might be worth an experiment to see what leaving out WM_MEASUREITEM does, though I usually discover with old code that I usually had perfectly good reason for doing something that looks redundant.