C++ odd text behavior - random garbage text - c++
SOLVED
After I reinstalled my OS (2008 Server) I then noticed that there's something odd going on within my program.
Here's the link to part of the source http://phantomworksstudios.com/cpp/ss/sof-odd.h
Here's the code first:
custom-data.h
class INI_{
public:
const char* error;
stringstream CharToStr2;
Layout layout;
Settings settings;
string file;
int OpenFile(string open_file){
CharToStr2.str("");
ifstream SSMAIN_FILE_SETTINGS;
CharToStr2<<open_file;
cout<<"CharToStr: "<<CharToStr2<<endl;
cout<<"CharToStr.str(): "<<CharToStr2.str()<<endl;
cout<<"CharToStr.str.c_str(): "<<CharToStr2.str().c_str()<<endl;
SSMAIN_FILE_SETTINGS.open(CharToStr2.str().c_str());
if(!SSMAIN_FILE_SETTINGS){
CharToStr2<<" is currupt or not found!. Loading default configuration!";
cout<<"STRING1:"<<CharToStr2<<endl<<endl;
cout<<"STRING2:"<<CharToStr2.str()<<endl<<endl;
cout<<"STRING3:"<<CharToStr2.str().c_str()<<endl<<endl;
error=CharToStr2.str().c_str();
cout<<"ERROR:"<<error<<endl;
}
cout <<"CLASS INI_: "<<SSMAIN_FILE_SETTINGS<<" : "<<file<<endl<<endl;
}
};
INI_ SourceStudioConfiguration;
procedures.h
case WM_CREATE:
SSMAIN_EXPLORERWINDOW_MENU=LoadMenu(SSMAIN_HINSTANCE,MAKEINTRESOURCE(ID_EXPLORER_MENU));
SourceStudioConfiguration.layout.cx=0;
User_Buffer=32767;
OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&hToken);
GetUserProfileDirectory(hToken,InfoBuf,&User_Buffer);
User_Path=InfoBuf;
// cout<<InfoBuf<<endl<<endl;
CharToStr<<InfoBuf<<"\\Source Studio\\preference.ini";
preference=CharToStr.str();
cout<<User_Path<<" : "<<preference<<endl<<endl;
// SourceStudioConfiguration.file=preference;
SourceStudioConfiguration.OpenFile(preference);
cout<<"CREATE:"<<SourceStudioConfiguration.error<<endl<<endl;
cout<<"Class File"<<SourceStudioConfiguration.file<<endl<<endl;
hbmPWSBUTTON = (HBITMAP)LoadBitmap(hInst_PWSBUTTON, MAKEINTRESOURCE(IMG_PWS_BUTTON));
cout<<"Load PWS Bitmap: "<<hbmPWSBUTTON<<endl;
hbmPWSCommandOVERVIEW=(HBITMAP)LoadBitmap(hInst_PWSCOMMANDTB, MAKENTRESOURCE(IMG_PWS_COMMAND_OVERVIEW));
hbmPWSCommandDOCUMENT=(HBITMAP)LoadBitmap(hInst_PWSCOMMANDTB, MAKEINTRESOURCE(IMG_PWS_COMMAND_DOCUMENT));
hbmPWSCommandNEWFILE=(HBITMAP)LoadBitmap(hInst_PWSCOMMANDTB, MAKEINTRESOURCE(IMG_PWS_COMMAND_NEWFILE));
hbmPWSCommandCLOSE=(HBITMAP)LoadBitmap(hInst_PWSCOMMANDTB, MAKEINTRESOURCE(IMG_PWS_COMMAND_CLOSE));
cout<<"CREATE:"<<SourceStudioConfiguration.error<<endl<<endl;
cout<<"Load PWS Command Toolbar Bitmap: "<<hbmPWSCommandOVERVIEW<<endl;
cout<<"CREATE 277:"<<SourceStudioConfiguration.error<<endl<<endl;
SSMAIN_REBARWINDOW = CreateWindowEx(WS_EX_TOOLWINDOW|WS_EX_TRANSPARENT, REBARCLASSNAME,NULL, WS_CHILD|WS_BORDER|RBS_VARHEIGHT|TBS_HORZ|RBS_BANDBORDERS|CCS_NODIVIDER|CCS_NOPARENTALIGN,0,0,0,0,hwnd, NULL, 0, 0);
SSMAIN_EXPLORERWINDOW=CreateWindowEx(WS_EX_TRANSPARENT,"button",NULL, BS_GROUPBOX|WS_CHILD,0,79,150,SSMAIN_HEIGHT-157,hwnd, (HMENU)SSMAIN_EXPLORERWINDOW_MENU, SSMAIN_EXPLORERBAR_HINSTANCE, 0);
//SSMAIN_EXPLORERWINDOW_REBAR=CreateWindowEx(WS_EX_TOOLWINDOW|WS_EX_TRANSPARENT, REBARCLASSNAME, NULL, WS_CHILD|WS_BORDER|RBS_VARHEIGHT|TBS_HORZ|RBS_BANDBORDERS|CCS_NODIVIDER|CCS_NOPARENTALIGN, 0,0,0,0,SSMAIN_EXPLORERWINDOW,NULL,0,0);
SSMAIN_NAVIGATIONTOOLBAR=CreateWindowEx(WS_EX_TOOLWINDOW|WS_EX_TRANSPARENT, "TOOLBARWINDOW32", NULL, WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|TBSTYLE_TOOLTIPS|TBSTYLE_FLAT|TBSTYLE_ALTDRAG|TBSTYLE_LIST|CCS_NODIVIDER|CCS_NOPARENTALIGN|CCS_ADJUSTABLE|CCS_NORESIZE, 0, 0, 0, 0,SSMAIN_REBARWINDOW, (HMENU)IDC_NAVIGATIONTOOLBAR, GetModuleHandle(NULL), NULL);
SSMAIN_EXPLORERWINDOW_OVERVIEW=CreateWindowEx(0,"button", NULL,BS_BITMAP|BS_USERBUTTON|BS_TEXT|WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS, 4, 12, 18, 18,SSMAIN_EXPLORERWINDOW, (HMENU)IDC_EXPLORERWINDOW_REBAR_COMMANDBAR, GetModuleHandle(NULL), NULL);
SSMAIN_EXPLORERWINDOW_DOCUMENT=CreateWindowEx(0, "button",NULL,BS_BITMAP|BS_USERBUTTON|BS_TEXT|WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS, 24, 12, 18, 18,SSMAIN_EXPLORERWINDOW, (HMENU)IDC_EXPLORERWINDOW_REBAR_COMMANDBAR, GetModuleHandle(NULL), NULL);
SSMAIN_EXPLORERWINDOW_NEWFILE=CreateWindowEx(0,"button",NULL, BS_BITMAP|BS_USERBUTTON|BS_TEXT|WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS, 44, 12, 18, 18,SSMAIN_EXPLORERWINDOW, (HMENU)IDC_EXPLORERWINDOW_REBAR_COMMANDBAR, GetModuleHandle(NULL), NULL);
SSMAIN_EXPLORERWINDOW_CLOSE=CreateWindowEx(0,"button",NULL, BS_BITMAP|BS_USERBUTTON|BS_TEXT|WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS, 62, 12, 18, 18,SSMAIN_EXPLORERWINDOW, (HMENU)IDC_EXPLORERWINDOW_REBAR_COMMANDBAR, GetModuleHandle(NULL), NULL);
//SSMAIN_PARENTCONTAINER=CreateWindow("SYSTABCONTROL32","", WS_EX_COMPOSITED|WS_CHILD|WS_VISIBLE,100,100,0,0,hwnd,(HMENU)ID_PARENTCONTAINER,SSMAIN_PARENTCONTAINER_HINSTANCE, NULL);
SSMAIN_STATIC_RTF_CONTAINER=CreateWindowEx(WS_EX_TRANSPARENT|WS_EX_CLIENTEDGE, "static","",WS_CHILD,0,0,0,0,hwnd,(HMENU)IDC_STATIC_RTF_CONTAINER,0,0);
SSMAIN_STATIC_RTFCONTROL_PARENT_HSCROLL=CreateWindow("SCROLLBAR","", WS_EX_COMPOSITED|WS_CHILD|WS_VISIBLE|SBS_BOTTOMALIGN,100,100,20,20,SSMAIN_STATIC_RTF_CONTAINER,(HMENU)IDC_STATIC_RTFCONTROL_PARENT_HSCROLL,SSMAIN_PARENTCONTAINER_HINSTANCE,NULL);
SSMAIN_LISTBOXRTFCOUNT= CreateWindowEx(0,"LISTBOX",NULL, WS_CHILD|WS_CLIPSIBLINGS|ECO_AUTOVSCROLL|LBS_NOINTEGRALHEIGHT|LBS_NOTIFY|WS_VISIBLE|WS_GROUP, 0,0,0,0,SSMAIN_STATIC_RTF_CONTAINER,(HMENU)IDC_LISTBOXRTFCOUNT,NULL,NULL);
SSMAIN_RTFCONTROL=CreateWindow("RICHEDIT","text", WS_CHILD|WS_VISIBLE|ES_MULTILINE|ES_AUTOHSCROLL|WS_VSCROLL|WS_HSCROLL|WS_GROUP, 0,0,0,0,SSMAIN_STATIC_RTF_CONTAINER,(HMENU)IDC_RTFCONTROL,SSMAIN_RTFCONTROL_HINSTANCE,0);
SSMAIN_TOOLBAR=CreateWindowEx(WS_EX_TOOLWINDOW|WS_EX_TRANSPARENT, "TOOLBARWINDOW32", NULL, WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|TBSTYLE_TOOLTIPS|TBSTYLE_FLAT|TBSTYLE_ALTDRAG|TBSTYLE_LIST|CCS_NODIVIDER|CCS_NOPARENTALIGN|CCS_ADJUSTABLE|CCS_NORESIZE, 0, 0, 0, 0,hwnd, (HMENU)IDC_TOOLBAR, GetModuleHandle(NULL), NULL);
SSMAIN_STATUSBAR = CreateWindow("MSCTLS_STATUSBAR32", "", WS_EX_COMPOSITED|WS_CHILD|WS_VISIBLE, 100, 100, 0, 0, hwnd, NULL, 0, NULL);
cout<<"CREATE 300:"<<SourceStudioConfiguration.error<<endl<<endl; SendMessage(SSMAIN_STATUSBAR,SB_SETPARTS,(WPARAM)3,(LPARAM)&panes);
SSMAIN_TOOLBARSYNTAX = CreateWindowEx(WS_EX_TOOLWINDOW|WS_EX_TRANSPARENT, "TOOLBARWINDOW32", NULL, WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|TBSTYLE_TOOLTIPS|TBSTYLE_FLAT|TBSTYLE_ALTDRAG|TBSTYLE_LIST|CCS_NODIVIDER|CCS_NOPARENTALIGN|CCS_ADJUSTABLE|CCS_NORESIZE, 0, 0, 0, 0,SSMAIN_REBARWINDOW, (HMENU)IDC_TOOLBARSYNTAX, GetModuleHandle(NULL), NULL);
SSMAIN_PWSBUTTON = CreateWindowEx(WS_EX_TRANSPARENT, "static", NULL, SS_BITMAP|TBSTYLE_TOOLTIPS|SS_NOTIFY|WS_CHILD|WS_VISIBLE, 50, 50, 32, 32, hwnd, (HMENU)IDC_PWSBUTTON, 0, 0);
SSMAIN_TOOLTIP = CreateWindowEx(0, TOOLTIPS_CLASS, 0, WS_POPUP|TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwnd, 0, SSMAIN_HINSTANCE, 0);
Now for some reason after SSMAIN_RTFCONTROL=CreateWindow("RICHEDIT","... when I display cout<<"CREATE 300:"<<SourceStudioConfiguration.error<<endl<<endl; the text is all random text. Now if I used the same thing before SSMAIN_RTFCONTROL=CreateWindow("RICHEDIT","... it will display correctly like it should.
My question is why is it doing that?
Also if I ignore SSMAIN_RTFCONTROL=CreateWindow("RICHEDIT","... as comment it will work like it should but then after some more lines on the cmd window it will display as random text again.
Is there something going on that I don't see? Like too much info going on where it start to mess with the error space and maybe setting something within it and it shouldn't?
Also as far as I can remember I didn't have this problem before I reinstalled my os.
Thanks and I'm really confused about this and if you need anymore info let me know and I'll post them
Also guys I tried to format the code by applying spaces like it said, but at times it doesn't allow any spaces in front of the line and other times it does so I don't know what's up with that.
ok guys here's the solution even though I don't know why if that makes any sense...
class INI_{
public:
const char* error;
stringstream CharToStr2;
string errordesc;
Layout layout;
Settings settings;
string file;
int OpenFile(string open_file){
CharToStr2.str("");
ifstream SSMAIN_FILE_SETTINGS;
CharToStr2<<open_file;
cout<<"CharToStr: "<<CharToStr2<<endl;
cout<<"CharToStr.str(): "<<CharToStr2.str()<<endl;
cout<<"CharToStr.str.c_str(): "<<CharToStr2.str().c_str()<<endl;
SSMAIN_FILE_SETTINGS.open(CharToStr2.str().c_str());
if(!SSMAIN_FILE_SETTINGS){
CharToStr2<<" is currupt or not found!. Loading default configuration!";
cout<<"STRING1:"<<CharToStr2<<endl<<endl;
cout<<"STRING2:"<<CharToStr2.str()<<endl<<endl;
cout<<"STRING3:"<<CharToStr2.str().c_str()<<endl<<endl;
errordesc=CharToStr2.str();
error=errordesc.c_str();
cout<<"ERROR:"<<error<<endl;
}
cout <<"CLASS INI_: "<<SSMAIN_FILE_SETTINGS<<" : "<<file<<endl<<endl;
}
};
Noticed that I added a variable string errordesc and assigned the source stream to that, then assigned errordesc to error
Related
How to add files to build and read them in Code Blocks?
I want to write only-exe application and I must load an image. What I have to do? Project Manager: https://dawidsk.gamejolt.io/images/ScreenShot_20190727141153.png (Sorry for bad English) Loading image code: void AddControls(HWND hWnd) { hWarning = CreateWindowW(L"Static", NULL, WS_VISIBLE | WS_CHILD | SS_BITMAP, 0, 0, windowHeight, windowWidth, hWnd, NULL, NULL, NULL); SendMessageW(hWarning, STM_SETIMAGE, IMAGE_BITMAP,(LPARAM) hWarningImage); } void LoadImages() { hWarningImage = (HBITMAP)LoadImageW(NULL, L"warning.bmp", IMAGE_BITMAP, windowHeight, windowWidth, LR_LOADFROMFILE); } When I remove warning.bmp from root folder of exe, it's not displaying it. EDIT: Now I know that I must use resource.rc. How can I load image from it?
You can follow this document to load it: https://learn.microsoft.com/en-us/windows/win32/menurc/bitmap-resource syntax: nameID BITMAP "warning.bmp" EDIT: After this, you could load the bitmap with the instance. define your nameID with a value, such as #define nameID 40001 Then loadimage with nameID and instance handle, remove the LR_LOADFROMFILE: LoadImageW(hInstance,MAKEINTRESOURCE(nameID),IMAGE_BITMAP, windowHeight, windowWidth, 0);
Resize cursor is showing on the border of a fixed dialog frame
It is a bit difficult to provide you with a minimal working example here but I am going to try and explain this issue that I have only just noticed. The Context So, I have a regular CDialogEx derived class, defined like this: class CChristianLifeMinistryStudentsDlg : public CDialogEx I have set it up so that the borders will not resize: The main application (also CDialogEx based) has a fixed window. That behaves correct. From the menu the user displays a resizable dialogue (an editor). On this dialog is a button the user can press which will in turn display the popup modal dialog I am referring to. What Happens When this dialog is displayed I have noticed this when you hover the mouse over the dialog borders: I don't understand why this is happening. Cursor Management In the "editor" that spawns this popup window I do have some cursor management like this: BOOL CChristianLifeMinistryEditorDlg::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { if (CPersistentWaitCursor::WaitCursorShown()) { RestoreWaitCursor(); return TRUE; } return CDialogEx::OnSetCursor(pWnd, nHitTest, message); } But, I have tried temporarily to invoke this popup from my main application dialog which does not have an cursor management and the result is still the same. Spy Results As requested I have just used Spy to examine the window styles: As anticipated we suddenly have WS_THICKFRAME set, when it was not in the resource editor! So In my RC file the dialog has the DS_MODALFRAME flag set but at runtime it ends up having the WS_THICKFRAME set. As far as I am aware I never make these changes for these affected dialog objects. Update I have found out the following: BOOL CChristianLifeMinistryStudentsDlg::OnInitDialog() { LONG_PTR lStyle = GetWindowLongPtr(GetSafeHwnd(), GWL_STYLE); if (lStyle & WS_THICKFRAME) AfxMessageBox(_T("Thick")); else if (lStyle & DS_MODALFRAME) AfxMessageBox(_T("Modal")); CDialogEx::OnInitDialog(); If I put the check code before the CDialogEx::OnInitDialog(); call the style is set as DS_MODALFRAME. But if I put the same check code after the CDialogEx::OnInitDialog(); call it is then changed to WS_THICKFRAME. Why? OK So, the CDialogEx::OnInitDialog method calls CWnd::LoadDynamicLayoutResource(LPCTSTR lpszResourceName). This in turn calls CWnd::InitDynamicLayout(). And in that method it does this: if (!bIsChild && (pDialog != NULL || pPropSheet != NULL)) { CRect rect; GetClientRect(&rect); ModifyStyle(DS_MODALFRAME, WS_POPUP | WS_THICKFRAME); ::AdjustWindowRectEx(&rect, GetStyle(), ::IsMenu(GetMenu()->GetSafeHmenu()), GetExStyle()); SetWindowPos(NULL, 0, 0, rect.Width(), rect.Height(), SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } There we go. So it is because I am using CDialogEx as my base class. Is this a bug in MFC? Clarification The "Editor" (parent window of the popup that owns the button) does use dynamic layout functonality: But in this instance the popup does not need to. But it is because my popup is derived from CDialogEx that this is happening. The plot thickens So this is the MFC code that is always called with CDialog::OnInitDialog: BOOL CWnd::LoadDynamicLayoutResource(LPCTSTR lpszResourceName) { if (GetSafeHwnd() == NULL || !::IsWindow(GetSafeHwnd()) || lpszResourceName == NULL) { return FALSE; } // find resource handle DWORD dwSize = 0; LPVOID lpResource = NULL; HGLOBAL hResource = NULL; if (lpszResourceName != NULL) { HINSTANCE hInst = AfxFindResourceHandle(lpszResourceName, RT_DIALOG_LAYOUT); HRSRC hDlgLayout = ::FindResource(hInst, lpszResourceName, RT_DIALOG_LAYOUT); if (hDlgLayout != NULL) { // load it dwSize = SizeofResource(hInst, hDlgLayout); hResource = LoadResource(hInst, hDlgLayout); if (hResource == NULL) return FALSE; // lock it lpResource = LockResource(hResource); ASSERT(lpResource != NULL); } } // Use lpResource BOOL bResult = CMFCDynamicLayout::LoadResource(this, lpResource, dwSize); // cleanup if (lpResource != NULL && hResource != NULL) { UnlockResource(hResource); FreeResource(hResource); } if (bResult) { InitDynamicLayout(); } return bResult; } For some reason this call BOOL bResult = CMFCDynamicLayout::LoadResource(this, lpResource, dwSize); is return TRUE. As a result the dialog eventually calls InitDynamicLayout. In my other dialogs that are popups this does not happen. Instead, bResult ends up as FALSE and thus the frame is not resized. So why does it think it worked?
Worked it out. I don't remember doing this but for some reason some of my controls on the dialog had dynamic properties set. For example: I had to set all of these properties back to None. Then it behaved. You can easily tell if a given dialog resource has any dynamic properties by opening your resource file in a text editor. For example: IDD_DIALOG_OUR_CHRISTIAN_LIFE_AND_MINISTRY_MATERIAL AFX_DIALOG_LAYOUT BEGIN 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 50, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 50, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 50, 0, 0, 0, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 END If something like the above is present then your dialog will be deemed as having a dynamic layout, and thus the settings for the dialog are modified: ModifyStyle(DS_MODALFRAME, WS_POPUP | WS_THICKFRAME); The resource will look like this when it has no dynamic control properties: IDD_DIALOG_OUR_CHRISTIAN_LIFE_AND_MINISTRY_MATERIAL AFX_DIALOG_LAYOUT BEGIN 0 END I chose to manually reset each control via the IDE. However, I guess you could modify the text file manually. As to why I had controls with dynamic properties in the first place, well, I can't tell you. I might have been fiddling in the past with the dialog and not realised the side effect to the border frame. Or, possibly, I may have copied controls from one resource on to another and it carried the dyanmic values. The interesing side note is that whilst the MFC code set the border as thick, it did not change it sufficiently to enable dialog resizing. But that is another matter! At least we now know the cause of the issue and how to easily identify the dialogs in the resource that have dynamic layouts.
How to correctly retrieve Unicode text from a control?
Here is an example of Unicode: I avoided to use a win32 application for for brevity sake: In main I created an edit control, a button to retrieve text from it and adds it to the listbox when pressed. So I used an object of struct MSG and blocked in a while loop peeking the messages from the message queue. int main(){ // An edit control where I can add any unicode text to. HWND hEdit = CreateWindowExW(WS_EX_CLIENTEDGE, L"Edit", L"你好! 你好吗?", WS_BORDER | WS_VISIBLE | WS_SYSMENU, 200, 100, 250, 70, 0, 0, GetModuleHandle(NULL), NULL); // A listobx to receive the content of the edit control when pressing the button get text. HWND hLstBx = CreateWindowExW(WS_EX_CLIENTEDGE, L"Listbox", NULL, WS_BORDER | WS_VISIBLE | WS_OVERLAPPEDWINDOW, 500, 100, 170, 400, 0, 0, GetModuleHandle(NULL), NULL); // A button when pressed adds the content of the edit to the listbox. HWND hGetText = CreateWindowExW(WS_EX_CLIENTEDGE, L"Button", L"中文", WS_BORDER | WS_VISIBLE, 450, 300, 100, 70, 0, 0, GetModuleHandle(NULL), NULL); // msg struct to pass to GetMessage to receive the messages from the queue. MSG msg; // blocking and getting messages from the queue. while (GetMessageW(&msg, 0, 0, 0)) { // some virtual keys translation. TranslateMessage(&msg); // sending the message to the specified window. DispatchMessageW(&msg); // Now after the messages sent to the target Window I check which control the message has been passed to, So if it is the button then: if (msg.message == WM_LBUTTONDOWN && msg.hwnd == hGetText) { std::wstring wstrBuff; int txtLen = SendMessageW(hEdit, WM_GETTEXTLENGTH, 0, 0); // SendMessageW(hEdit, WM_GETTEXT, txtLen + 1, (LPARAM)wstrBuff.c_str()); // MessageBoxW(0, wstrBuff.c_str(), 0, 0); wchar_t lpTxt[MAX_PATH]; SendMessageW(hEdit, WM_GETTEXT, MAX_PATH, (LPARAM)lpTxt); SendMessageW(hLstBx, LB_ADDSTRING, 0, (LPARAM)lpTxt); MessageBoxW(0, lpTxt, L"你好! 你好吗?", 0); //delete[]lpTxt; } } std::wcout << std::endl << std::endl; std::wcin.get(); return 0; } Every thing works fine except: If I un-comment the lines above I get run-time error facing the assertion message showing me the txtLen and the size of the text of the edit control. Is this because there's some string overlapping? If I enter a small text it works fine but with a text about 14 characters I get the error. Also is that the right way to pass std::wstring.c_str() to SendMessageW() to get the text? One last question: How to correctly and effectively retrieve Unicode text from a control? How to use LPWSTR with dynamic memory: I don't want to exhaust stack. NB: I saved the source file as utf8 /BOM otherwise I get unreadable characters. Thanks to the members who helped me about that.
Sending (LPARAM)wstrBuff.c_str() will return a pointer to read-only buffer with a single null symbol, not a buffer of txtLen + 1 symbols. If you are using latest VS (with C++17 standard support) you can modify your code to supply a proper pointer: std::wstring wstrBuff; wstrBuff.resize(txtLen + 1); const LRESULT copied_symbols_count = SendMessageW ( hEdit , WM_GETTEXT , static_cast<WPARAM>(wstrBuff.size()) , reinterpret_cast<LPARAM>(wstrBuff.data()) ); if(copied_symbols_count == txtLen) { assert(L'\0' == wstrBuff.back()); wstrBuff.pop_back(); // get rid of terminating null } else { wstrBuff.clear(); // something went wrong... } Note that C++17 standard adds non-const-qualified wstring::data() method that can be safely used to obtain a pointer to writable buffer.
Getting battery information for Laptop and put it in label in C++
I am doing an App for laptops Called Batterlizer, It will get all the information about the battery, So everything was going well until I wanted to get the battery percent and other things , so here is my code: SYSTEM_POWER_STATUS BatteryPower; if(GetSystemPowerStatus( &BatteryPower )) { long unsigned int BatteryFull = BatteryPower.BatteryLifeTime; const char BatteryFullTime[900] = {BatteryFull}; BatteryLeftText = CreateWindow("static", "Battery Life:",WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0, 0, 100, 20,hwnd, (HMENU)(501),(HINSTANCE) GetWindowLong (hwnd, GWL_HINSTANCE), NULL); UpdatedBatteryText = CreateWindow("static",BatteryFullTime, WS_VISIBLE | WS_CHILD | WS_TABSTOP, 90, 0, 50, 20, hwnd, (HMENU)(501),(HINSTANCE) GetWindowLong (hwnd, GWL_HINSTANCE),NULL); } the problem is , it says strange letters when it comes to BatteryFullTime, Any Ideas guys?
Try the following: char szBatteryLifeBuffer[900] = {0}; sprintf(szBatteryLifeBuffer, "%lu", BatteryFull); SetWindowText(UpdatedBatteryText, szBatteryLifeBuffer); // This also should work, too. // SendMessage(UpdatedBatteryText, WM_SETTEXT, 0, (LPARAM)(LPTSTR)szBatteryLifeBuffer); Get rid of // This does not work. const char BatteryFullTime[900] = {BatteryFull};
You're using C instead of C++, that makes it harder. In C++ : std::string BatteryFullTime = std::to_string(BatteryFull); No need to care about length, or remember details of the conversion function. However: SetWindowText(UpdatedBatteryText, BatteryFullTime.c_str()); The Windows function does need a C string, but it's easy to get a C string from the C++ string.
c++ win32 edit box cursor not flashing
I'm a newbie in windows programming and am continuously running into different kinds of problems, most of which I have been able to solve by myself. My problem at hand is the caret (or cursor) shown in text areas. The thing that indicates where you are typing your text? Well it is shown, at least, but it doesn't blink like it should. I have an EDIT box created in WM_CREATE like so: case WM_CREATE: { if(!logged) { HWND userField = CreateWindow( "EDIT", // Predefined class; Unicode assumed NULL, // Button text WS_VISIBLE | WS_CHILD | WS_BORDER | ES_LEFT, // Styles C_WIDTH/2 - 80, // x position C_HEIGHT - 240, // y position 160, // Button width 25, // Button height hwnd, // Parent window NULL, // No menu. (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL); // Pointer not needed. // initialize NONCLIENTMETRICS structure NONCLIENTMETRICS ncm; ncm.cbSize = sizeof(ncm); // obtain non-client metrics SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0); // create the new font HFONT hNewFont = CreateFontIndirect(&ncm.lfMessageFont); // set the new font SendMessage(userField, WM_SETFONT, (WPARAM)hNewFont, 0); } } break; That is all code concerning the edit box. I'm sorry if I'm not being clear enough or my supply of code is lacking; I'm unsure of what parts of code is relevant here and what are irrelevant. I don't think I should paste my whole code here, either. The problem, again, is that the caret in the textbox (userField) does not blink. Please ask for more details if you need them.
Using your code, I didn't get a flashing caret. But then i added: SetFocus( userField ); and voilà, a flashing caret :-)
This may not be the problem the OP was experiencing, but I was experiencing the same symptom, and I'm posting my solution here in case someone else experiences this problem... In short, if you subclass an edit control, and handle the WM_SETFOCUS event, you need to call DefSubclassProc() or your caret won't show up. Presumably, you can call ShowCaret() yourself, but you're probably safer just calling DefSubclassProc() in case there's other processing that needs to happen.
After playing around - making my code a bit tidier and stuff - I accidentally solved this on my own I changed HWND userField = CreateWindow( "EDIT", // Predefined class; Unicode assumed NULL, // Button text WS_VISIBLE | WS_CHILD | WS_BORDER | ES_LEFT, // Styles C_WIDTH/2 - 80, // x position C_HEIGHT - 240, // y position 160, // Button width 25, // Button height hwnd, // Parent window NULL, // No menu. (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL); // Pointer not needed. Into HWND userField = CreateWindow("EDIT", NULL, WS_VISIBLE | WS_CHILD | WS_BORDER | ES_LEFT, C_WIDTH/2 - 80, C_HEIGHT - 240, 160, 25, hwnd, NULL, g_hInstance, NULL); The only difference there is the hInstance: in the first code it was apparently wrong. I changed it into my global reference of hInstance.