【文本框属性设置】
设为多行文本框:Multiline=True
允许按回车键换行:Want Return=True
自动换行:Auto HScroll=False
在最后一行按回车键,自动向上滚动:Auto VScroll=True
显示垂直滚动条:Vertical Scroll=True
【程序代码】
main.c:
#include <stdio.h>
#include <tchar.h>
#include <time.h>
#include <Windows.h>
#include <CommCtrl.h>
#include <WindowsX.h>
#include "resource.h"#pragma comment(lib, "comctl32.lib")
#pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' language='*' publicKeyToken='6595b64144ccf1df'\"")void add_new_line(HWND hedit, HWND hstatic)
{char str[100];char *p, *q;int i, len, size;time_t t;struct tm tm;// 根据当前时间生成新行内容time(&t);localtime_s(&tm, &t);strftime(str, sizeof(str), "当前时间: %Y-%m-%d %H:%M:%S", &tm);len = GetWindowTextLengthA(hedit) + 2 + strlen(str); // 新文本长度 = 原有文本长度 + 换行符长度 + 新行长度size = len + 1; // 新文本长度 + 字符串结束符长度p = (char *)malloc(size);if (p != NULL){// 新添加一行GetWindowTextA(hedit, p, size); // 获取原有文本if (p[0] != '\0')strcat_s(p, size, "\r\n"); // 添加换行符strcat_s(p, size, str); // 添加新行SetWindowTextA(hedit, p); // 设置新文本// 计算总行数i = 0;for (q = p; q != NULL; q = strstr(q, "\r\n")){i++;if (memcmp(q, "\r\n", 2) == 0)q += 2;}_snprintf_s(str, sizeof(str), sizeof(str), "行数: %d", i);SetWindowTextA(hstatic, str);free(p);// 光标移动到末尾SetFocus(hedit);Edit_Scroll(hedit, i, 0);Edit_SetSel(hedit, len, len);}
}LRESULT CALLBACK DlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{int wmId;HWND hedit, hstatic;switch (uMsg){case WM_COMMAND:wmId = LOWORD(wParam);switch (wmId){case IDOK:hedit = GetDlgItem(hDlg, IDC_EDIT1);hstatic = GetDlgItem(hDlg, IDC_STATIC2);add_new_line(hedit, hstatic);break;case IDCANCEL:EndDialog(hDlg, 0);break;}case WM_INITDIALOG:break;}return 0;
}int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{int ret;InitCommonControls();ret = DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, DlgProc);return ret;
}
【程序运行结果】