Win32 Tab Control w/Multiple Rows - c++

I have a tab control in my Win32 application. The control is multi-row capable. When I resize the window such that the tab control is reduced in width, multiple rows show up. The problem is that when I click on one of the lower rows the tabs in the upper rows are blocked by the current tab's window( the tab control doesn't properly resize the content window of the current tab so that the upper rows are visible ). How do I account for this problem?
Here is code for my resize function:
RECT cr;
GetClientRect( pHdr->hWndTab, &cr );
TabCtrl_AdjustRect( pHdr->hWndTab, FALSE, &cr );
OffsetRect( &cr, cxMargin - cr.left, cyMargin - cr.top );
SetWindowPos( pHdr->hWndDisplay, 0, cr.left, cr.top, cr.right, cr.bottom, SWP_SHOWWINDOW );
This code comes from Microsoft website...
pHdr->hWndTab is the window handle for the tab control
pHdr->hWndDisplay is the window handle for the content window of the current tab
EDIT: Actually, after clicking the lower tabs, the upper tabs move to the top of control...however, they are still blocked by the content window...

I fixed the problem by adjusting the display rectangle after offsetting:
typedef struct tag_dlghdr
{
HWND hWndTab;
HWND hWndDisplay;
RECT rcDisplay;
DLGTEMPLATE *apRes[ MAX_PAGES ];
DLGPROC MsgProc[ MAX_PAGES ];
}DLGHDR
Resize( HWND hWndDlg )
{
DLGHDR *pHdr = ( DLGHDR * )GetWindowLong( hWndDlg, GWL_USERDATA );
DWORD dwDlgBase = GetDialogBaseUnits();
int cxMargin = LOWORD( dwDlgBase ) / 4;
int cyMargin = HIWORD( dwDlgBase ) / 8;
m_niCurTabSel = TabCtrl_GetCurSel( pHdr->hWndTab );
RECT cr;
GetClientRect( pHdr->hWndTab, &cr );
TabCtrl_AdjustRect( pHdr->hWndTab, FALSE, &cr );
OffsetRect( &cr, cxMargin - cr.left, cyMargin - cr.top );
CopyRect( &pHdr->rcDisplay, &cr );
TabCtrl_AdjustRect( pHdr->hWndTab, FALSE, &pHdr->rcDisplay );
SetWindowPos( pHdr->hWndDisplay, 0, pHdr->rcDisplay.left, pHdr->rcDisplay.top, pHdr->rcDisplay.right, pHdr->rcDisplay.bottom, SWP_SHOWWINDOW );
}

Related

C++ MFC Refresh Window

I am using Visual Studio 2010 with MFC and I am trying to make a rectangle that is red when a device is disconnected and green when it is. I have made the rectangle with the following code:
CRect lConnectStatus;
GetDlgItem( IDC_CONNECT_STATUS ) -> GetClientRect( &lConnectStatus );
GetDlgItem( IDC_CONNECT_STATUS ) -> ClientToScreen( &lConnectStatus );
ScreenToClient( &lConnectStatus );
mConnected.Create( GetSafeHwnd(), 10000 );
mConnected.SetPosition( lConnectStatus.left, lConnectStatus.top, lConnectStatus.Width(), lConnectStatus.Height() );
if( mDevice.IsConnected() ){
mConnected.SetBackgroundColor(0, 255, 0);
}
else{mConnected.SetBackgroundColor(0, 0, 255);}
I inserted this snippet into the OnInitDlg method and the rectangle does appear, but it doesn't change to green when the device gets connected. Is there anyway I can refresh the window so that the code is executed again and the colour changes to green?
What type of control is IDC_CONNECT_STATUS? If it is a static control you can eliminate all this code and handle WM_CTLCOLOR_STATIC in the parent dialog. Your message handler for that message will control the color of the static control. To refresh the static control call Invalidate on that control. That will cause it to call your WM_CTLCOLOR_STATIC message handler.
Solved It, As I am new to C++ I didn't know that putting the code snippet into the OnInitDlg() method wouldn't work. So I put the code into the OnPaint()method and used the functions Invalidate() and UpdateWindow() to force the window to refresh when the device was connected/disconnected. Thanks for your help.
Edit Thanks to Barmak for suggesting not to create the control in the OnPaint() method. I have updated the code below.
program::OnInitDlg(){
CRect lConnectStatus;
GetDlgItem( IDC_CONNECT_STATUS ) -> GetClientRect( &lConnectStatus );
GetDlgItem( IDC_CONNECT_STATUS ) -> ClientToScreen( &lConnectStatus );
ScreenToClient( &lConnectStatus );
mConnected.Create( GetSafeHwnd(), 10000 );
mConnected.SetPosition( lConnectStatus.left, lConnectStatus.top, lConnectStatus.Width(), lConnectStatus.Height() );
}
program::OnPaint(){
if( mDevice.IsConnected() ){
mConnected.SetBackgroundColor(0, 255, 0);
}
else{mConnected.SetBackgroundColor(0, 0, 255);}
}
program::Connect(){
Invalidate();
UpdateWindow();
}
program::disconnect(){
Invalidate();
UpdateWindow();
}

Window size of edit control/combobox is not properly adjusted when using MoveWindow or SetWindowPos

INTRODUCTION AND RELEVANT INFORMATION:
I am trying to implement listview control with editable items and subitems. Instead of regular listview look, items and subitems should have edit control, checkbox or combo box.
I am using raw WinAPI and C++. I am targeting Windows XP onwards.
MY EFFORTS TO SOLVE THE PROBLEM:
After researching here and on the Internet, I was able to only find examples in MFC. They all use LVN_BEGINLABELEDIT technique to implement this behavior.
Unfortunately I do not understand entirely this concept so I have decided to start from scratch ( I consider this also to be the best approach for improving ones programming skills ).
MY CONCEPT:
I have decided to catch NM_DBLCLK for listview and to get coordinates from there using ListView_GetItemRect or ListView_GetSubItemRect macro.
Then I would simply move the combobox/checkbox/edit control over corresponding item/subitem ( combobox/edit control/checkbox would be created as separate, hidden windows ).
After user finishes with input ( by pressing enter or changing focus ) I would simply hide the combobox/checkbox/edit control.
MY CURRENT RESULTS:
At the moment, I am stuck with the dimensions of combobox/edit control/checkbox not being the same as item/subitem dimensions, when moved above the item/subitem.
QUESTION:
Can my code example submitted below be improved to properly adjust combobox/edit control/checkbox window size to the size of the item/subitem? For now, I will only focus on this part of the problem, to keep this question as short as possible.
Here is the instruction for creating small application that illustrates the problem. Notice that I have tried to keep things as minimal as I could:
1.) Create default Win32 project in Visual Studio ( I use VS 2008 ).
2.) Add the following WM_CREATE handler to main window's procedure:
case WM_CREATE:
{
HWND hEdit = CreateWindowEx( 0,WC_EDIT, L"",
WS_CHILD | WS_VISIBLE | WS_BORDER | ES_CENTER | ES_AUTOHSCROLL,
250, 10, 100, 20, hWnd, (HMENU)1500, hInst, 0 );
HWND hComboBox = CreateWindowEx( 0,WC_COMBOBOX, L"",
WS_CHILD | WS_VISIBLE | WS_BORDER | CBS_DROPDOWNLIST,
100, 10, 100, 20, hWnd, (HMENU)1600, hInst, 0 );
HWND hwndLV = CreateWindowEx( 0, WC_LISTVIEW,
L"Editable Subitems",
WS_CHILD | WS_VISIBLE | WS_BORDER |
LVS_REPORT | LVS_SINGLESEL,
150, 100, 250, 150, hWnd, (HMENU)2000, hInst, 0 );
// set extended listview styles
ListView_SetExtendedListViewStyle( GetDlgItem( hWnd, 2000 ),
LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_DOUBLEBUFFER );
// add some columns
LVCOLUMN lvc = {0};
lvc.iSubItem = 0;
lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
lvc.fmt = LVCFMT_LEFT;
for (long nIndex = 0; nIndex < 5; nIndex++ )
{
wchar_t txt[50];
swprintf_s( txt, 50, L"Column %d", nIndex + 1 );
lvc.iSubItem = nIndex;
lvc.cx = 60;
lvc.pszText = txt;
ListView_InsertColumn( GetDlgItem( hWnd,2000 ), nIndex, &lvc );
}
// add some items
LVITEM lvi;
lvi.mask = LVIF_TEXT;
lvi.iItem = 0;
for( lvi.iItem = 0; lvi.iItem < 10; lvi.iItem++ )
for (long nIndex = 0; nIndex < 5; nIndex++ )
{
wchar_t txt[50];
swprintf_s( txt, 50, L"Item %d%d", lvi.iItem + 1, nIndex + 1 );
lvi.iSubItem = nIndex;
lvi.pszText = txt;
if( ! nIndex ) // item
SendDlgItemMessage( hWnd, 2000,
LVM_INSERTITEM, 0,
reinterpret_cast<LPARAM>(&lvi) );
else // sub-item
SendDlgItemMessage( hWnd, 2000,
LVM_SETITEM, 0,
reinterpret_cast<LPARAM>(&lvi) );
}
}
return 0L;
3.) Add the following handler for WM_NOTIFY in main window's procedure:
case WM_NOTIFY:
{
if( ((LPNMHDR)lParam)->code == NM_DBLCLK )
{
switch( ((LPNMHDR)lParam)->idFrom )
{
case 2000: // remember, this was our listview's ID
{
LPNMITEMACTIVATE lpnmia = (LPNMITEMACTIVATE)lParam;
// SHIFT/ALT/CTRL/their combination, must not be pressed
if( ( lpnmia->uKeyFlags || 0 ) == 0 )
{
// this is where we store item/subitem rectangle
RECT rc = { 0, 0, 0, 0 };
if( (lpnmia->iSubItem) <= 0 ) // this is item so we must call ListView_GetItemRect
{
// this rectangle holds proper left coordinate
// since ListView_GetItemRect with LVIR_LABEL flag
// messes up rectangle's left cordinate
RECT rcHelp = { 0, 0, 0, 0 };
// this call gets the length of entire row
// but holds proper left coordinate
ListView_GetItemRect( lpnmia->hdr.hwndFrom,
lpnmia->iItem, &rcHelp, LVIR_BOUNDS );
// this call gets proper rectangle except for the left side
ListView_GetItemRect( lpnmia->hdr.hwndFrom,
lpnmia->iItem, &rc, LVIR_LABEL );
// now we can correct the left coordinate
rc.left = rcHelp.left;
}
else // it is subitem, so we must call ListView_GetSubItemRect
{
ListView_GetSubItemRect( lpnmia->hdr.hwndFrom,
lpnmia->iItem, lpnmia->iSubItem,
LVIR_BOUNDS, &rc );
}
// convert listview client coordinates to parent coordinates
// so edit control can be properly moved
POINT p;
p.x = rc.left;
p.y = rc.top;
ClientToScreen( lpnmia->hdr.hwndFrom, &p );
ScreenToClient( hWnd, &p );
MoveWindow( GetDlgItem( hWnd, 1500 ),
p.x, p.y,
rc.right - rc.left,
rc.bottom - rc.top, TRUE );
// set focus to our edit control
HWND previousWnd = SetFocus( GetDlgItem( hWnd, 1500 ) );
}
}
break;
default:
break;
}
}
}
break;
And this is the result I get:
You can clearly see that top and bottom border of the edit control are not drawn properly. As for combobox, the width is properly adjusted, but height remains the same.
I have tried substituting MoveWindow call with SetWindowPos but the result was the same.
After further tampering, I have found out that NMITEMACTIVATE bugs when returning the rectangle of a subitem, if listview doesn't have LVS_EX_FULLROWSELECT style set. You can see this by simply commenting out the part in my WM_CREATE handler where I set this style. Maybe I am doing something wrong and this "bug" may be caused by my code, but I don't see the problem.
EDITED on September, 17th 2014:
After testing the values for iItem and iSubItem members of NMITEMACTIVATE structure when listview doesn't have LVS_EX_FULLROWSELECT I can verify that the bug is not in my code. It always returns iItem to be 0, no matter which subitem I click. This explains the faulty behavior I got when removing this style.
If any further info is required please leave a comment and I will act as soon as possible.
Thank you for your time and efforts to help.
The issue you're facing is multi-faceted.
Firstly, the default font of the edit control is larger (higher) than that of the list-view. You can fix this one quite trivially, by first getting the font from the list-view and then setting it to the edit control. Doing this will then make the bottom border of the control visible.
The next issue is that the caret of the edit control needs a pixel above and below it, to ensure that the control doesn't have its borders interfered with. In addition to this 1 pixel of 'space' you then need another pixel for the border.
Added to this second point, the dimensions calculated by rc.right - rc.left and rc.bottom - rc.top are 1 pixel too small. Think of a rect that starts at 1,1 and extends to 2,2 - this is a rect of 4 pixels - 2 wide and 2 high. Simply subtracting the top/left from the bottom/right would give you a width/height of only 1 pixel each. To fix this, you need to add 1 to each of these subtractions.
Finally, since the caret is exactly the height of the 'client-area' of each item/sub-item, you need to make the edit control 2 pixels taller than the item/sub-item, and start 1 2 pixels higher than it does currently.
Here's the output I get when making the suggested changes:
And here's the changes/additions I made.
1. Get/Set the font. (inserted after creating the list-view and before setting its extended style)
HFONT lvFont = (HFONT)SendDlgItemMessage(hWnd, 2000, WM_GETFONT, 0, 0);
SendDlgItemMessage(hWnd, 1500, WM_SETFONT, (WPARAM)lvFont, TRUE);
2. Set the window position/size
MoveWindow( GetDlgItem( hWnd, 1500 ),
p.x, p.y-2,
1+ rc.right - rc.left,
1+ 2 + rc.bottom - rc.top, TRUE );
Finally, contrast this against the original output from your code:
UPDATE:
Here's a snapshot of the appearance when the built-in label editing functionality is used (LVS_EDITLABELS style)

Expected and actual printing results do not match

INTRODUCTION AND RELEVANT INFORMATION:
I am trying to bypass another problem in my application by trying to do printing/print preview on my own.
I am trying to create a table that would look like in the picture below:
I am using C++ and WinAPI, on WindowsXP SP3. I work in MS Visual Studio 2008.
I do not have a printer, so I am testing the results by printing to MS OneNote and XPS file.
PROBLEM:
Text is obtained from database and is of variable length. Since it might not fit into the original cell, I will need to expand the cell and fit the text appropriately, like in the above image.
SIDE EFFECT:
The result of my testing code gives inconsistent results regarding font size.
In OneNote the print result seems fine :
However, in XPS it looks different :
MY EFFORTS TO SOLVE THIS TASK:
I have checked MSDN documentation to get started. So far I am able to successfully draw text and lines on a printing surface.
I have used DrawTextEx to perform word breaking ( by using flag DT_WORDBREAK ).
To obtain the size of the printing area I have used GetDeviceCaps, and to obtain printer device context I have used print property sheet.
QUESTIONS:
IMPORTANT REMARKS:
If the following questions are considered too broad please leave a comment and I will edit my post. I still believe that my mistakes are minor and can be explained in a single post.
1. Can you explain me how to adjust cells so the entire string can fit ?
Why is my font inconsistently drawn ?
As always, here are the instructions for creating SSCCE :
1) In Visual Studio, create default Win32 project.
2) in stdafx.h file comment out #define WIN32_LEAN_AND_MEAN so print property sheet can work properly.
3) In stdafx.h add the following, below #include <windows.h> line :
#include <windowsx.h>
#include <commctrl.h>
#pragma comment( linker, "/manifestdependency:\"type='win32' \
name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \
processorArchitecture='*' publicKeyToken='6595b64144ccf1df' \
language='*'\"")
4) Add the following function above window procedure :
// hWnd is the window that owns the property sheet.
HRESULT DisplayPrintPropertySheet(HWND hWnd)
{
HRESULT hResult;
PRINTDLGEX pdx = {0};
LPPRINTPAGERANGE pPageRanges = NULL;
// Allocate an array of PRINTPAGERANGE structures.
pPageRanges = (LPPRINTPAGERANGE) GlobalAlloc(GPTR, 10 * sizeof(PRINTPAGERANGE));
if (!pPageRanges)
return E_OUTOFMEMORY;
// Initialize the PRINTDLGEX structure.
pdx.lStructSize = sizeof(PRINTDLGEX);
pdx.hwndOwner = hWnd;
pdx.hDevMode = NULL;
pdx.hDevNames = NULL;
pdx.hDC = NULL;
pdx.Flags = PD_RETURNDC;
pdx.Flags2 = 0;
pdx.ExclusionFlags = 0;
pdx.nPageRanges = 0;
pdx.nMaxPageRanges = 10;
pdx.lpPageRanges = pPageRanges;
pdx.nMinPage = 1;
pdx.nMaxPage = 1000;
pdx.nCopies = 1;
pdx.hInstance = 0;
pdx.lpPrintTemplateName = NULL;
pdx.lpCallback = NULL;
pdx.nPropertyPages = 0;
pdx.lphPropertyPages = NULL;
pdx.nStartPage = START_PAGE_GENERAL;
pdx.dwResultAction = 0;
// Invoke the Print property sheet.
hResult = PrintDlgEx(&pdx);
if ( ( hResult == S_OK )
&& ( pdx.dwResultAction == PD_RESULT_PRINT ) )
{
// User clicked the Print button,
// so use the DC and other information returned in the
// PRINTDLGEX structure to print the document.
/***************** IMPORTANT INFO : ********************/
/****** I have added additional test code here *********/
/**** please refer to the edited part of this post *****/
/***************** at the very bottom !! ***************/
DOCINFO diDocInfo = {0};
diDocInfo.cbSize = sizeof( DOCINFO );
diDocInfo.lpszDocName = L"Testing printing...";
//******************** initialize testing font *****************//
HFONT font, oldFont;
long lfHeight = -MulDiv( 14, GetDeviceCaps( pdx.hDC, LOGPIXELSY), 72 );
font = CreateFont( lfHeight,
0, 0, 0, FW_BOLD, TRUE, FALSE, FALSE, 0, 0, 0,
0, 0, L"Microsoft Sans Serif" );
oldFont = SelectFont( pdx.hDC, font );
SetBkMode( pdx.hDC, TRANSPARENT );
SetTextColor( pdx.hDC, RGB( 255, 0, 0 ) );
//******************** end of initialization ******************//
if( StartDoc( pdx.hDC, &diDocInfo ) > 0 )
{
if( StartPage( pdx.hDC ) > 0 )
{
// get paper dimensions
int pageWidth, pageHeight;
pageWidth = GetDeviceCaps( pdx.hDC, HORZRES );
pageHeight = GetDeviceCaps( pdx.hDC, VERTRES );
/************ draw a testing grid ***************/
// draw vertical lines of the grid
for( int i = 0; i < pageWidth; i += pageWidth / 4 )
{
MoveToEx( pdx.hDC, i, 0, NULL );
LineTo( pdx.hDC, i, pageHeight );
}
// draw horizontal lines of the grid
for( int j = 0; j < pageHeight; j += pageWidth / 10 )
{
MoveToEx( pdx.hDC, 0, j, NULL );
LineTo( pdx.hDC, pageWidth, j );
}
/************************************************/
// test rectangle for drawing the text
RECT r;
r.left = 0;
r.top = 0;
r.right = 550;
r.bottom = 100;
// fill rectangle with light gray brush
// so we can see if text is properly drawn
FillRect( pdx.hDC, &r,
(HBRUSH)GetStockObject(LTGRAY_BRUSH) );
// draw text in test rectangle
if( 0 == DrawTextEx( pdx.hDC,
L"This is test string!",
wcslen( L"This is test string!" ),
&r,
DT_CENTER | DT_WORDBREAK | DT_NOCLIP, NULL ) )
// for now pop a message box saying something went wrong
MessageBox( hWnd, L"DrawText failed!", L"Error", MB_OK );
if( EndPage( pdx.hDC ) < 0 )
// for now pop a message box saying something went wrong
MessageBox( hWnd, L"EndDoc failed!", L"Error", MB_OK );
}
EndDoc( pdx.hDC );
SelectFont( pdx.hDC, oldFont );
DeleteFont( font );
}
}
if (pdx.hDevMode != NULL)
GlobalFree(pdx.hDevMode);
if (pdx.hDevNames != NULL)
GlobalFree(pdx.hDevNames);
if (pdx.lpPageRanges != NULL)
GlobalFree(pPageRanges);
if (pdx.hDC != NULL)
DeleteDC(pdx.hDC);
return hResult;
}
5) In WM_COMMAND handler, modify case IDM_ABOUT like this :
case IDM_ABOUT: // test our printing here
{
if( FAILED( DisplayPrintPropertySheet( hWnd ) ) )
MessageBox( hWnd,
L"Can't display print property sheet!",
L"Error", MB_OK );
}
//DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
EDITED on June, 8th 2014 :
After the block if ( ( hResult == S_OK ) && ( pdx.dwResultAction == PD_RESULT_PRINT ) ) in the submitted SSCCE I have added the following for testing purposes :
int xDpi = GetDeviceCaps( pdx.hDC, LOGPIXELSX ),
yDpi = GetDeviceCaps( pdx.hDC, LOGPIXELSY );
int mapMode = GetMapMode( pdx.hDC );
wchar_t displayDPI[50];
swprintf_s( displayDPI, 50, L" xDPI = %s , yDPI = %s", xDpi, yDpi );
MessageBox( hWnd, displayDPI, L"", MB_OK );
switch( mapMode )
{
case MM_ANISOTROPIC:
MessageBox( hWnd, L"MM_ANISOTROPIC", L"", MB_OK );
break;
case MM_HIENGLISH:
MessageBox( hWnd, L"MM_HIENGLISH", L"", MB_OK );
break;
case MM_HIMETRIC:
MessageBox( hWnd, L"MM_HIMETRIC", L"", MB_OK );
break;
case MM_ISOTROPIC:
MessageBox( hWnd, L"MM_ISOTROPIC", L"", MB_OK );
break;
case MM_LOENGLISH:
MessageBox( hWnd, L"MM_LOENGLISH", L"", MB_OK );
break;
case MM_LOMETRIC:
MessageBox( hWnd, L"MM_LOMETRIC", L"", MB_OK );
break;
case MM_TEXT:
MessageBox( hWnd, L"MM_TEXT", L"", MB_OK );
break;
case MM_TWIPS:
MessageBox( hWnd, L"MM_TWIPS", L"", MB_OK );
break;
default:
MessageBeep(0);
break;
}
In both cases mapping mode was the same ( MM_TEXT ) but for XPS I got xDPI = 600 , yDPI = 600 in the MessageBox while OneNote had xDPI = 300 , yDPI = 300.
This leads to the conclusion that comments made by member * Carey Gregory* were correct -> with the same characteristics virtual printers will reproduce the same result. This also explains why OneNote printed properly into XPS when I tested it, and why my application failed. To solve this problem I need to find DPI aware solution...
EDITED on June, 9th 2014 :
Using GDI+ to create font and draw text I was able to get consistent results ( DPI is no longer a problem ). Still, if anyone knows how to achieve the same result using only GDI I would be still interested.
The only thing left for me is to draw a proper grid so the text can fit into cells properly.
EDITED on June, 10th 2014 :
After carefully reading through this MSDN link I was able to alter the font creating code to achieve ( in my opinion ) stable results ( the actual height of the font ends up way smaller, but I could use bigger number I guess ) :
font = CreateFont(
// DPI aware, thanks to the below equation ( or so it seems... )
lfHeight / ( GetDeviceCaps( pdx.hDC, LOGPIXELSY ) / 96 ),
0, 0, 0, FW_BOLD, TRUE, FALSE, FALSE, 0, 0, 0, // remained the same
0, 0, L"Microsoft Sans Serif" ); // remained the same
Just to be safe, I will try to stick with GDI+ but will update this post with the testing results when GDI and the mentioned equation is used in case someone else stumbles upon the same problem. I just hope it will save that persons time...
The problem is simple. You are adjusting the font size (in pixels) to match the DPI of the device you're drawing to, but you're not adjusting the size of the rectangle. Since your mapping mode is MM_TEXT both are measured in pixels, and your bounding box is effectively half the size on the device with twice the resolution.
The solution is to scale the rectangle similarly to the way you scale the font size. In this case since you've determined that these coordinates are correct at 300 DPI, that's the constant we'll scale relative to.
RECT r;
r.left = 0 * GetDeviceCaps(pdx.hDC, LOGPIXELSX) / 300;
r.top = 0 * GetDeviceCaps(pdx.hDC, LOGPIXELSY) / 300;
r.right = 550 * GetDeviceCaps(pdx.hDC, LOGPIXELSX) / 300;
r.bottom = 100 * GetDeviceCaps(pdx.hDC, LOGPIXELSX) / 300;
Regarding your edit of June 10, it only works because you've made the font much smaller so that it fits in both the full-size bounding box and the half-size one. I'd recommend going back to the original definition you had for font size, which is consistent with most other Windows applications.

Listbox change width dynamically

Listboxes do not auto-resize. The best we've got is:
SendMessage(my_listbox, LB_SETHORIZONTALEXTENT, 1000, 0);
MS helpfully notes that "...a list box does not update its horizontal extent dynamically."
(why the heck not...but I digress)
How can the width be set dynamically to avoid truncating the text of a message longer than 1000px?
if I understand the question... :-)
You'll essentially need to measure all of the items in the list box and calculate the maximum width of the list box contents, and then adjust the width of the listbox.
Here's some code from this project (that adds a automatic horizontal scrollbar to listboxes). This snippet is called when the font changes but it demonstrates (roughly) what's needed:
static void OnSetFont( HWND hwnd, HFONT hFont )
//
// Font has changed!
// We need to measure all of our items and reset the horizontal extent of the listbox
{
CData *pData = reinterpret_cast< CData * >( ::GetProp( hwnd, g_pcszDataProperty ) );
pData->m_hFont = hFont;
//
// Set up a HDC...
HDC hdc = GetDC( hwnd );
HGDIOBJ hOld = SelectObject( hdc, pData->m_hFont );
//
// Record the average width for use as our 'fudge factor' later.
TEXTMETRIC tm;
GetTextMetrics( hdc, &tm );
pData->m_nAvergeCharWidth = tm.tmAveCharWidth;
pData->m_nMaxWidth = 0;
//
// This is used as our item buffer. Saves us from having to handle the reallocation
// for different string lengths
CArray< TCHAR, TCHAR > arrBuffer;
//
// Quick reference to make the code below read better
CArray< int, int > &arrWidth = pData->m_arrItemWidth;
//
// The main loop. Iterate over the items, get their text from the listbox and measure
// it using our friendly little helper function.
const UINT uCount = arrWidth.GetSize();
for( UINT u = 0; u < uCount; u++ )
{
const int nLength = ::SendMessage( hwnd, LB_GETTEXTLEN, u, 0 );
arrBuffer.SetSize( nLength + 1 );
::SendMessage( hwnd, LB_GETTEXT, u, (WPARAM)arrBuffer.GetData() );
const int nItemWidth = BaseMeasureItem( pData, hwnd, hdc, arrBuffer.GetData() );
pData->m_arrItemWidth.SetAt( u, nItemWidth );
if( nItemWidth > pData->m_nMaxWidth )
{
pData->m_nMaxWidth = nItemWidth;
}
}
//
// Now, either set the horizontal extent or not, depending on whether we think we need it.
if( pData->m_nMaxWidth > pData->m_nClientWidth )
{
::SendMessage( hwnd, LB_SETHORIZONTALEXTENT, pData->m_nMaxWidth + pData->m_nAvergeCharWidth, 0 );
}
else
{
::SendMessage( hwnd, LB_SETHORIZONTALEXTENT, 0, 0 );
}
//
// The usual release of resources.
SelectObject( hdc, hOld );
ReleaseDC( hwnd, hdc );
}
and...
static int BaseMeasureItem( CData *pData, HWND hwnd, HDC hdc, LPCTSTR pcszText )
//
// Measure and item and adjust the horizontal extent accordingly.
// Because the HDC is already set up we can just do it.
// We return the width of the string so our caller can use it.
{
SIZE size;
::GetTextExtentPoint32( hdc, pcszText, _tcslen( pcszText ), &size );
if( size.cx > pData->m_nMaxWidth )
{
pData->m_nMaxWidth = size.cx;
if( pData->m_nMaxWidth > pData->m_nClientWidth )
{
::SendMessage( hwnd, LB_SETHORIZONTALEXTENT, pData->m_nMaxWidth + pData->m_nAvergeCharWidth, 0 );
}
}
return size.cx;
}

Static Text Color

I have written Following code which will apply color to all static text in one window, but
I want to apply two different colors in one window like ID:1234 where ID is another color and 1234 will be different color in one window. How can I do this? here is what i have done:
case WM_CTLCOLORSTATIC:
SetBkColor( hdc, COLORREF( :: GetSysColor( COLOR_3DFACE) ) );
//sets bckcolor of static text same as window color
if ( ( HWND ) lParam == GetDlgItem( hWnd, IDC_PID) )
{
SetTextColor( ( HDC ) wParam, RGB( 250, 50, 200));
return ( BOOL ) CreateSolidBrush ( GetSysColor( COLOR_3DFACE) );
}
break;
I'm not sure I understand your problem. Your code looks pretty much ok. One point worth noting is that you are responsible for cleaning up resources that you allocate. With the code above you are leaking the HBRUSH object created through a call to CreateSolidBrush. Since you don't need a custom brush you should rather be using GetSysColorBrush.
As a matter of taste I would filter on the control ID rather than its window handle using GetDlgCtrlID. Incorporating the changes your code should look like this:
case WM_CTLCOLORSTATIC:
switch ( GetDlgCtrlID( (HWND)lParam ) )
{
case IDC_PID:
//sets bckcolor of static text same as window color
SetBkColor( (HDC)wParam, COLORREF( GetSysColor( COLOR_3DFACE ) ) );
SetTextColor( (HDC)wParam, RGB( 250, 50, 200) );
return (INT_PTR)GetSysColorBrush( COLOR_3DFACE );
default:
// Message wasn't handled -> pass it on to the default handler
return 0;
}