Can I make a property sheet without resource script? - windows

I'd like to add controls to a property sheet without resource script, rather using pure code.
The reason for this I'd like to create a property sheet(mimicking C#'s property grid), calling C routines/WINAPI, from another language, binary-compatible to C; but I'd like to define everything with code, without need of a resource script. Is this possible or the way to go is write my own property-sheet-like, with underlying CreateWindow*() calls? (different approaches to do this are welcome, I'm new to WINAPI) which I suppose property sheet use behind the scenes

Found the solution! I found this post from Raymond Chen where he shows how do that.
the main code goes like this:
BOOL FakeMessageBox(HWND hwnd, LPCWSTR pszMessage, LPCWSTR pszTitle)
{
BOOL fSuccess = FALSE;
HDC hdc = GetDC(NULL);
if (hdc) {
NONCLIENTMETRICSW ncm = { sizeof(ncm) };
if (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, 0, &ncm, 0)) {
DialogTemplate tmp;
// Write out the extended dialog template header
tmp.Write<WORD>(1); // dialog version
tmp.Write<WORD>(0xFFFF); // extended dialog template
tmp.Write<DWORD>(0); // help ID
tmp.Write<DWORD>(0); // extended style
tmp.Write<DWORD>(WS_CAPTION | WS_SYSMENU | DS_SETFONT | DS_MODALFRAME);
tmp.Write<WORD>(2); // number of controls
tmp.Write<WORD>(32); // X
tmp.Write<WORD>(32); // Y
tmp.Write<WORD>(200); // width
tmp.Write<WORD>(80); // height
tmp.WriteString(L""); // no menu
tmp.WriteString(L""); // default dialog class
tmp.WriteString(pszTitle); // title
// Next comes the font description.
// See text for discussion of fancy formula.
if (ncm.lfMessageFont.lfHeight < 0) {
ncm.lfMessageFont.lfHeight = -MulDiv(ncm.lfMessageFont.lfHeight,
72, GetDeviceCaps(hdc, LOGPIXELSY));
}
tmp.Write<WORD>((WORD)ncm.lfMessageFont.lfHeight); // point
tmp.Write<WORD>((WORD)ncm.lfMessageFont.lfWeight); // weight
tmp.Write<BYTE>(ncm.lfMessageFont.lfItalic); // Italic
tmp.Write<BYTE>(ncm.lfMessageFont.lfCharSet); // CharSet
tmp.WriteString(ncm.lfMessageFont.lfFaceName);
// Then come the two controls. First is the static text.
tmp.AlignToDword();
tmp.Write<DWORD>(0); // help id
tmp.Write<DWORD>(0); // window extended style
tmp.Write<DWORD>(WS_CHILD | WS_VISIBLE); // style
tmp.Write<WORD>(7); // x
tmp.Write<WORD>(7); // y
tmp.Write<WORD>(200-14); // width
tmp.Write<WORD>(80-7-14-7); // height
tmp.Write<DWORD>(-1); // control ID
tmp.Write<DWORD>(0x0082FFFF); // static
tmp.WriteString(pszMessage); // text
tmp.Write<WORD>(0); // no extra data
// Second control is the OK button.
tmp.AlignToDword();
tmp.Write<DWORD>(0); // help id
tmp.Write<DWORD>(0); // window extended style
tmp.Write<DWORD>(WS_CHILD | WS_VISIBLE |
WS_GROUP | WS_TABSTOP | BS_DEFPUSHBUTTON); // style
tmp.Write<WORD>(75); // x
tmp.Write<WORD>(80-7-14); // y
tmp.Write<WORD>(50); // width
tmp.Write<WORD>(14); // height
tmp.Write<DWORD>(IDCANCEL); // control ID
tmp.Write<DWORD>(0x0080FFFF); // static
tmp.WriteString(L"OK"); // text
tmp.Write<WORD>(0); // no extra data
// Template is ready - go display it.
fSuccess = DialogBoxIndirect(g_hinst, tmp.Template(),
hwnd, DlgProc) >= 0;
}
ReleaseDC(NULL, hdc); // fixed 11 May
}
return fSuccess;
}

Related

How do I make a combobox show a tab control like VS' when setting a color?

I mean this control:
When you click on this, instead of regular options, a tab control with the colors is displayed. How can I do this? is this a owner-draw combobox or something else? I'm aware on how draw text, rectangles, images, etc with a owner-draw combobox but I don't know how add controls over there. I have no code to show yet because I have no idea how do that. I've tried something like call CreateWindow() in WM_DRAWITEM using the values from DRAWITEMSTRUCT.rcItem but I can't make a control inside the groupbox's client area, the button gets behind the control.
Looks like you are looking for CBN_DROPDOWN.
Sent when the list box of a combo box is about to be made visible. The
parent window of the combo box receives this notification code through
the WM_COMMAND message.
Some code:
HWND hWndComboBox = CreateWindow(
WC_COMBOBOX,
TEXT(""),
WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST,
10, 20, 70, 17,
hWnd, (HMENU)IDB_COMBOX, hInstance, NULL);
...
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDB_COMBOX:
{
switch (HIWORD(wParam))
{
case CBN_DROPDOWN:
{
CHOOSECOLOR cc; // common dialog box structure
static COLORREF acrCustClr[16]; // array of custom colors
static DWORD rgbCurrent; // initial color selection
// Initialize CHOOSECOLOR
ZeroMemory(&cc, sizeof(cc));
cc.lStructSize = sizeof(cc);
cc.hwndOwner = hWnd;
cc.lpCustColors = (LPDWORD)acrCustClr;
cc.rgbResult = rgbCurrent;
cc.Flags = CC_FULLOPEN | CC_RGBINIT;
ChooseColor(&cc);
}
break;
...
Debug:

MFC: Have CDockablePane receive ON_NOTIFY_REFLECT messages for a CTreeCtrl?

The MFC Wizard created a project with a CWorkSpaceBar which in my case is actually based on CBCGPDockingControlBar, the MFC equivalent is CDockablePane. The wizard also created a m_wndTree based on CBCGPTreeCtrl (CTreeCtrl). It created it in its OnCreate() like this:
CRect rectDummy;
rectDummy.SetRectEmpty();
// Create tree control:
const DWORD dwViewStyle = WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS;
if (!m_wndTree.Create(dwViewStyle, rectDummy, this, 1))
{
TRACE0("Failed to create workspace view\n");
return -1; // fail to create
}
Now I would like to handle some of the TreeView notifications so I added these to the CWorkSpaceBar message map:
ON_NOTIFY_REFLECT(TVN_ITEMEXPANDING, &CWorkSpaceBar::OnTvnItemExpanding)
ON_NOTIFY_REFLECT(TVN_GETDISPINFO, &CWorkSpaceBar::OnTvnGetDispInfo)
However, I'm not getting the notification messages? Is there something else I need to do to make it work?
You appear to be confusing the ON_NOTIFY_REFLECT and ON_NOTIFY handlers; or rather, the windows for which those handlers should be defined.
From what you have described, your CWorkSpaceBar class/object is the parent of the tree-view (CTreeCtrl) object; so, when an item is expanded in that tree-view, that parent pane receives a WM_NOTIFY message and the relevant ON_NOTIFY handler (if defined in the message-map) is called. The ON_NOTIFY_REFLECT handler allows the actual tree-view itself to intercept/receive the notification.
In my projects, I have a similar situation, and the class(es) derived from CDockablePane (such as my UserPane) have message map entries like the following, which work as expected:
ON_NOTIFY(TVN_ITEMEXPANDING, IDR_USRTV, &UserPane::OnItemExpand)
Note: The IDR_USRTV is the ID value that I give to the tree-view, in its Create function, as shown below; in your example code, you have used the value of 1 (which may or may not be advisable).
int UserPane::OnCreate(CREATESTRUCT *pCreateStruct)
{
CRect rc; rc.SetRectEmpty();
const DWORD trvstyle = WS_CHILD | WS_VISIBLE |
TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS | TVS_EDITLABELS;
if (CDockablePane::OnCreate(pCreateStruct) == -1) return -1;
if (!m_wndTView.Create(trvstyle, rc, this, IDR_USRTV)) return -1;
//...
A basic outline for the OnItemExpand member function is as follows:
void UserPane::OnItemExpand(NMHDR *pNotifyStruct, LRESULT *result)
{
*result = 0;
NMTREEVIEW *pTV = reinterpret_cast<NMTREEVIEW *>(pNotifyStruct);
HTREEITEM hItem = pTV->itemNew.hItem;
uintptr_t itemData = m_wndTView.GetItemData(hItem);
if (pTV->action == TVE_EXPAND) {
//...
}
else if (pTV->action == TVE_COLLAPSE) {
//...
}
return;
}

Mfc Font binding and Rich Edit Control RICHEDIT50W does not display Unicode Properly

Latest update:
Well, I found a culprit of some sort. I changed the control to RichEdit20W from the 50W and it displays the Hangul (Korean) now. I did not have to change any other code except for the init, added AfxInitRichEdit2(), and commented out the LoadLibrary(L"MsftEdit.dll"). The AfxInitRichEdit5() is not available for VS2010. All things being equal and Rich Edit 4.1 has been available since VS2005, it should have worked. I can't upgrade to VS2015 right now so I'm stuck. I'm going to offer a bounty though for anybody who can make the Hangul work with 50W and VS2010.
I have a dilemma that I can't seem to solve.
I have an mfc Unicode app that uses CEdit and CRicheditCtrl.
The Rich Edit is 50W loaded from MsftEdit.dll and verified with Spy++
that the class name is RICHEDIT50W.
My problem:
I'm using the same Font Courier New for both the CEdit and CRichEditCtrl.
As a test, I used some of the Hangul symbols to see the output for both
controls.
CEdit outputs ᄀᄁᄂᄃᄄᄅᄆᄇᄈ
while the
CRichEditCtrl outputs a box for each character, like there is no glyph for it.
If they are using the same font, shouldn't I see the same output characters?
I think that font-binding is not a problem, both have the same default font.
Can anybody solve this riddle ?
Thanks in advance!
Note that this happens with some other character sets as well, not just Hangul
Update
I looked at the VS2010 WordPad example, it uses CRichEditView but it
provides wrappers to access the embedded CRichEditCtrl.
I thought I could glean some info but I can't see how they are doing the
Rich Edit control calls.
This is how I am generating the font's for both controls.
But, I'm showing specifically the Rich Edit part.
The doc's say that Font binding should handle switching from the default
font to the font at the current insertion point.
I am doing insertion mostly at the end using
ctrl.SetSel(-1,-1);
ctrl.ReplaceSel( str );
And, according to the doc's, this should change to the correct font as needed,
if other than the default font.
In the WordPad sample, if I paste in the Hangul text, the font switches to
Gulim.
Here is my code:
LOGFONT lf;
int pitch = 10;
memset(&lf, 0, sizeof(LOGFONT));
HDC hdc = ::GetDC(NULL);
lf.lfHeight = -MulDiv( pitch, GetDeviceCaps(hdc, LOGPIXELSY), 72);
lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
lstrcpy(lf.lfFaceName, _T("Courier New") );
lf.lfWeight = FW_NORMAL;
lf.lfCharSet = ANSI_CHARSET; // English, but use DEFAULT_CHARSET if not
lf.lfQuality = DEFAULT_QUALITY;
if ( !m_Font.CreateFontIndirect(&lf) )
{ // Ours didn't work, create a system default fixed font
// ( Ignore, example for post only. Never gets called though )
//memset(&lf, 0, sizeof(LOGFONT));
//::GetObject(GetStockObject(ANSI_FIXED_FONT), sizeof(LOGFONT), &lf);
//m_Font.CreateFontIndirect(&lf);
}
// Save the generated Font LOGFONT
m_lf = lf;
// Set the default Font CHARFORMAT2
memset( &m_cfDefaultFont, 0, sizeof(m_cfDefaultFont) );
m_cfDefaultFont.cbSize = sizeof(m_cfDefaultFont);
m_cfDefaultFont.dwMask = CFM_CHARSET | CFM_FACE | CFM_WEIGHT ;
m_cfDefaultFont.bCharSet = m_lf.lfCharSet;
lstrcpy( m_cfDefaultFont.szFaceName, m_lf.lfFaceName );
m_cfDefaultFont.wWeight = m_lf.lfWeight;
// Finally set the font in the controls
m_RichEdit.SetFont( &m_Font );
// Same effect as m_RichEdit.SetFont()
//m_RichEdit.SendMessage(EM_SETCHARFORMAT, SCF_ALL, &m_cfDefaultFont);
// This displays nothing but 'box' glyphs
m_RichEdit.SetWindowTextW(_T("ᄃᄄᄅᄆᄇᄈᄉᄊᄋᄌᄍᄎ"));
Update 2
This is how I initialize the Rich Edit in the app.
And shows the usage of 50W in a dialog control.
-- winapp.cpp
BOOL CMyApp::InitInstance()
{
// ...... //
CString strRichEdit = _T("Msftedit.dll");
m_hMsfteditDll = AfxLoadLibrary( strRichEdit );
if ( m_hMsfteditDll == NULL )
{
CString str;
str.Format(_T("Error: Cannot find Rich Edit component %s"), strRichEdit );
AfxMessageBox(str);
return FALSE;
}
return TRUE;
}
int CRegexFormatApp::ExitInstance()
{
if ( m_hMsfteditDll != NULL )
AfxFreeLibrary( m_hMsfteditDll );
return CWinAppEx::ExitInstance();
}
// =========================
-- .rc
CONTROL "",IDC_RICH_EDIT,"RICHEDIT50W",WS_VSCROLL | WS_HSCROLL,40,15,148,28
-- Dlg.h
CRichEditCtrl m_RichEdit;
-- Dlg.cpp
void Dlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_RICH_EDIT, m_RichEdit); // Use .rc setting to Create/Attach
}
BOOL Dlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
CreateAndSetRichFont(); // Code shown above
m_RichEdit.SetWindowTextW( ... );
}
This code should work in a Unicode project:
BOOL CMyApp::InitInstance()
{
CWinApp::InitInstance();
LoadLibrary(L"MsftEdit.dll");
...
}
BOOL CMyDialog::OnInitDialog()
{
CDialog::OnInitDialog();
static CRichEditCtrl redit;
CWnd *wnd = &redit;
wnd->Create(MSFTEDIT_CLASS, L"ᄃᄄᄅᄆᄇᄈᄉᄊᄋᄌᄍᄎ",
WS_CHILD | WS_VISIBLE, CRect(0,0,300,300), this, 1001, 0);
...
//redit is not to be mixed up with controls created in dialog editor.
}
Edit ----------------
NONCLIENTMETRICS info = { sizeof(info) };
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(info), &info, 0);
LOGFONT logfont = info.lfMessageFont;
//CClientDC has automatic cleanup, use it instead of GetDC
CClientDC dc(this);
logfont.lfHeight = -MulDiv(abs(logfont.lfHeight), dc.GetDeviceCaps(LOGPIXELSY), 76);
CFont font;
font.CreateFontIndirect(&logfont);
m_RichEdit.SetFont(&font);
m_RichEdit.SetWindowText(L"ᄃᄄᄅᄆᄇᄈᄉᄊᄋᄌᄍᄎ");
m_RichEdit.SetSel(1, 1);
CString test = L"(Test, ελληνικά)";
//Test to make sure we can see Unicode text
AfxMessageBox(test);
m_RichEdit.ReplaceSel(test);
//optional:
//get default CHARFORMAT
CHARFORMAT2 charFormat;
//m_RichEdit.GetSelectionCharFormat(charFormat);
m_RichEdit.GetDefaultCharFormat(charFormat);

PollEvent() in Win32

I'm trying to mimic SFML's PollEvent(Event &event) function in Windows. It seems far more complicated that I imagined. Note that I already encapsulated the window procedure function in my class.
There could be many "window events" in my program - WindowMoved, WindowResized etc.
My first attempt was to have a private data member in the class, defined as WindowEvent *_lastWindowEvent. This variable will be set if PeekMessage() returns a non-zero value, just before DispatchMessage() is called. Then, winProc() will edit _lastWindowEvent, depending on the message it will receive.
The drawback here is that I noticed that winProc() may be called with a MSG parameter regardless of DispatchMessage(), like with the WM_SETCURSOR message.
Then I thought about having instead a std::queue<WindowEvent> in my class, when winProc() continuously pushes WindowEvents to it. The problem here is that sometimes the window procedure function keeps getting messages and won't return. This happens when I drag-move the window (then the WM_MOVING message is continuously called, along with other messages). The code after DispatchMessage() will not run until I release my mouse. This also happens when resizing the window.
Did I grasp anything wrong? How do you think such PollEvent function can be implemented?
Given that PollEvent is primarily for a game loop style design, you can probably poll for what you need while simultaneously servicing the Windows event loop:
class Window
{
HWND _hwnd; // Win32 handle to the window
RECT _lastWindowSize; // last known window size
POINT _lastMousePos; // last known mouse position on window
BYTE _lastKeyboardState[256]; // last known key state
std::list<Event> _events; // unprocessed events
public:
bool PollEvent(Event* pEvent);
};
bool Window::PollEvent(Event* pEvent)
{
// return any previously queued events
if (_events.size() > 0)
{
*pEvent = _events.pop_front();
return true;
}
// process 1 windows event message
if (PeekMessage(&msg, _hWnd, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.msg == WM_QUIT)
{
*pEvent = EXIT_EVENT; // special handling for WM_QUIT
return true;
}
}
// -----------------------------------------
// poll keyboard state
BYTE kbState[256];
GetKeyboardState(kbState);
bool isKeyboardEvent = false;
if (memcmp(_lastKeyboardState, kbState, 256) != 0)
{
// not shown
// compute diff of kbState and _lastKeyboardState
// generate a keyboard event and add to the queue
Event kbevt;
kbevt.type = KeyEvent;
kbevt.code = <computed code based on diff above>
_events.push_back(kbevt);
}
memcpy(_lastKeyboardState, kbState, 256);
// -----------------------------------------
// -----------------------------------------
// poll window size changes
RECT rectWindowSize;
int width, height, oldwidth, oldheight;
GetClientRect(&rectWindowSize);
width = rectWindowSize.right - rectWindowSize.left;
height = rectWindowSize.bottom - rectWindowSize.top;
oldwidth = _lastWindowSize.right - _lastWindowSize.left;
oldheight = _lastWindowSize.bottom - _lastWindowSize.top;
if ((width != oldwidth) || (height != oldheight))
{
Event sizeEvent;
sizeEvent.type = SizeEvent;
sizeEvent.width = width;
sizeEvent.height = height;
_events.push_back(kbevt);
}
_lastWindowSize = rectWindowSize;
// -----------------------------------------
// not shown - computing mouse position, joystick position, text stuff
// if at least one event was queued - return it now
if (_events.size() > 0)
{
*pEvent = _events.pop_front();
return true;
}
return false;
}

How to Store Dynamically in the List Control of MFC in Visual Studio?

I am working on the dialog based applciation using MFC in visual studio 2010. I used the list control as report type to display . I managed to display some hardcoded data on that output window. Here is the code. what's wrong in the code
void CuserspecificationDlg::OnAdd() // This function add file by clicking on Add button
{
// TODO: Add your control notification handler code here
CFileDialog ldFile(TRUE);
// Show the File Open dialog and capture the result
if (ldFile.DoModal() == IDOK)
{
CStdioFile fileName;
//TCHAR buf[100]; // it is declared in h file
while( fileName.ReadString(buf,99))
{}
fileName.Close();
}
void CuserspecificationDlg::InsertItems()
{
//
list.cx = 100;
list.pszText = "Project"; // this project is the column heading of the dialog
list.iSubItem = 2;
::SendMessage(hWnd ,LVM_INSERTCOLUMN,
(WPARAM)1,(WPARAM)&list);
SetCell(hWnd,"1",0,0);
SetCell(hWnd,buf,0,1); // these 1,G,X,X are the hardcoded entries.
SetCell(hWnd,"G ",0,2);
SetCell(hWnd," X",0,3);
//----- //
}
How to display that buf? It doesnt work . buf is not diplaying the content from file properly. As some characters 1,G and X are visible in the output window but the buf statement doesnt show the characters properly. .. What's wrong in the code.
To add items to a list control, you first need to create a column:
LVCOLUMN lvCol;
lvCol.mask = LVCF_TEXT | LVCF_WIDTH;
lvCol.pszText = L"Column Header Text";
m_CListCtrl.InsertColumn(0, &lvCol);
// ...
You then insert items into the list control of struct type LVITEM
LVITEM item;
item.mask = LVIF_TEXT;
item.pszText = "Column Text";
item.iItem = numItem; // Item number
item.iSubItem = 0; // Sub item number (column number)
m_CListCtrl.InsertItem(&item);

Resources