我認爲下面的代碼應該是不言自明的。如何將文本追加到文本框?
#include <Windows.h>
static HWND textBoxInput;
static HWND button;
static HWND textBoxOutput;
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int CALLBACK WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR cmdLine,int nCmdShow)
{
HWND hMainWindow;
WNDCLASS wc = {};
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = "Main's window class";
wc.hInstance = hInstance;
RegisterClass(&wc);
hMainWindow = CreateWindow(wc.lpszClassName,"Append text main window",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,500,400,NULL,NULL,hInstance,NULL);
error=GetLastError();
if(hMainWindow == NULL) return 1;
textBoxInput = CreateWindowEx(WS_EX_CLIENTEDGE, "Edit", NULL,WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL, 10, 10, 300, 21, hMainWindow, NULL, NULL, NULL);
button = CreateWindowEx(WS_EX_CLIENTEDGE,"Button","Append",WS_CHILD | WS_VISIBLE | ES_CENTER, 10, 41,75,30,hMainWindow,NULL,NULL,NULL);
textBoxOutput = CreateWindowEx(WS_EX_CLIENTEDGE,"Edit",TEXT("->This content is untouchable and unreadable!<-"),WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_AUTOVSCROLL | ES_MULTILINE | ES_READONLY ,10,81,500,90,hMainWindow,NULL,NULL,NULL);
ShowWindow(hMainWindow,SW_SHOW);
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_COMMAND:
if((HWND)lParam == button)
{
TCHAR* buffer = new TCHAR[150];
GetWindowText(textBoxInput,buffer,150);
SetWindowText(textBoxOutput,buffer);
//AppendWindowText(textBoxOutput,buffer,150) - I haven't found such function;
delete [] buffer;
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
HBRUSH pedzel;
pedzel = CreateSolidBrush(RGB(10,250,10));
FillRect(hdc, &ps.rcPaint, pedzel);
EndPaint(hwnd, &ps);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
簡言之:這個程序創建兩個文本框和一個啓動複製從所述第一到所述第二內容的處理的按鈕。 SetWindowText
功能導致清潔輸出盒,顯然不是所期望的。傑裏·Cofinn的回答後
更新
SendMessage(textBoxOutput,EM_SETSEL,-1,-1); //no difference between passing 0 or -1
SendMessage(textBoxOutput,EM_REPLACESEL,TRUE,(LPARAM)buffer);
出人意料的是,它預規劃文本。我讀過關於EM_SETSEL的the documentation,我仍然想知道爲什麼不把原始輸入放在最後。
有關設置和調整選擇的更多信息,則[.NET參考源用於'TextBoxBase.AppendText'](https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/的WinForms/TextBoxBase。cs,5194bb23bd26ed3e)可能會有所幫助 – Slai