Ozz*_*zah 3 c++ windows winapi
我有一个EditBox HWND tbLog,以及以下函数(不起作用):
void appendLogText(char* newText)
{
int len = GetWindowTextLength(tbLog);
char* logText = new char[len + strlen(newText) + 1];
GetWindowText(tbLog, logText, len);
strcat(logText, newText);
SendMessage(tbLog, WM_SETTEXT, NULL, (LPARAM)TEXT(logText));
delete[] logText;
}
Run Code Online (Sandbox Code Playgroud)
我称之为:
appendLogText("Put something in the Edit box.\r\n");
appendLogText("Put something else in the Edit box.\r\n");
Run Code Online (Sandbox Code Playgroud)
首先,TEXT()实际上做了什么?我曾尝试过/不使用它:(LPARAM)logText而且(LPARAM)TEXT(logText)就我所见,没有任何区别.
第二,我在追加功能中做错了什么?如果我注释掉我的delete行,那么第一次运行append函数时,我的Editbox中会出现垃圾,然后是消息.我第二次运行它,程序崩溃了.如果我没有注释掉它,那么它第一次就会崩溃.
Chr*_*cke 10
我会在C中重写函数,如下所示:
void appendLogText(LPCTSTR newText)
{
DWORD l,r;
SendMessage(tbLog, EM_GETSEL,(WPARAM)&l,(LPARAM)&r);
SendMessage(tbLog, EM_SETSEL, -1, -1);
SendMessage(tbLog, EM_REPLACESEL, 0, (LPARAM)newText);
SendMessage(tbLog, EM_SETSEL,l,r);
}
Run Code Online (Sandbox Code Playgroud)
保存和恢复现有选择或控件的重要性对于任何想要选择并从控件中复制一些文本的人来说都变得非常烦人.
此外,使用LPCTSTR可确保在使用多字节或unicode字符集构建时可以调用该函数.
TEXT宏不合适,应该用于包装字符串文字:
LPCTSTR someString = TEXT("string literal");
Run Code Online (Sandbox Code Playgroud)
Windows NT操作系统本身是unicode,因此构建多字节应用程序效率很低.在字符串文字上使用TEXT(),而用LPTSTR代替'char*'有助于将此转换为unicode.但实际上,在Windows上显式切换到unicode编程可能是最有效的:代替char,strlen,std :: string,使用wchar_t,std :: wstring,wsclen和L"string literals".
将项目构建设置切换为Unicode将使所有Windows API函数都需要unicode字符串.
由于EM_SETSEL的WPARAM仅仅取消选择任何选择但不移动插入点,因此引起我的迟来的注意.所以答案应该被修改为(也未经测试):
void appendLogText(HWND hWndLog, LPCTSTR newText)
{
int left,right;
int len = GetWindowTextLength(hWndLog);
SendMessage(hWndLog, EM_GETSEL,(WPARAM)&left,(LPARAM)&right);
SendMessage(hWndLog, EM_SETSEL, len, len);
SendMessage(hWndLog, EM_REPLACESEL, 0, (LPARAM)newText);
SendMessage(hWndLog, EM_SETSEL,left,right);
}
Run Code Online (Sandbox Code Playgroud)