Win32 SDK_Edit控件用法
1获得控件句柄
HWND hEdit2 = ::GetDlgItem(hWnd, IDC_EDIT2);
WINUSERAPI
HWND
WINAPI
GetDlgItem(
_In_opt_ HWND hDlg, //父窗口句柄
_In_ int nIDDlgItem); //控件ID
2赋值
SetDlgItemText(hWnd, IDC_EDIT1, TEXT(“给Edit控件赋值方法一”));
HWND hEdit2 = ::GetDlgItem(hWnd, IDC_EDIT2);
SendMessage(hEdit2, WM_SETTEXT, 0, (LPARAM)TEXT(“给Edit控件赋值方法二”));
3获得控件中的字符串长度
方法1:
int nLen = SendMessage(hEdit2, WM_GETTEXTLENGTH, 0, 0);
方法2:
int nLen2=GetWindowTextLength(hEdit2);
4获得控件中的字符串
TCHAR tchar[128],tchar2[128];
GetDlgItemText(hWnd, IDC_EDIT1, tchar, 128); //方法1
SendMessage(hEdit2, WM_GETTEXT, 128, (LPARAM)tchar2); //方法2
5全选中消息,EM_SETSEL
SendMessage(hEdit1, EM_SETSEL, 0, -1); //全选中
SendMessage(hEdit2, EM_SETSEL, 1, 6); //1为起始位置,6为结束位置的选中
6获得焦点
SendMessage(hEdit2, WM_SETFOCUS, 0, 0);//获得焦点
7修改控件颜色
//在消息中捕获WM_CTLCOLOREDIT消息
case WM_CTLCOLOREDIT:
{
//OnCtlColorEdit(wParam, lParam);
HDC hdc = (HDC)wParam;
if (hEdit2 == (HWND)lParam || hEdit1 == (HWND)lParam)
{
SetTextColor(hdc, RGB(224, 255, 255)); //设置字体颜色
SetBkMode(hdc, OPAQUE); //设置背景色模式
SetBkColor(hdc, RGB(0, 0, 255)); //设置背景颜色
return (INT_PTR)CreateSolidBrush(RGB(0, 0, 255)); //返回一个背景颜色刷子
}
break;
}
8捕获EN_CHANGE消息,控件输入变化消息,是在WM_COMMAND命令消息中捕获
case WM_COMMAND:
{
if (LOWORD(wParam) == IDC_EDIT4 && HIWORD(wParam)==EN_CHANGE)
{
return On_EnChange(wParam, lParam);
}
}
break;
9其他消息
EN_CHANGE:编辑框的内容被用户改变了,与WN_UPDATE不同,这是在编辑框正文被刷新后才发出的消息
EN_ERRSPACE: 编辑框无法申请足够的动态内存来满足需要
EN_HCCROLL: 用户在水平滚动条上单击鼠标
EN_KILLFOCUS; 编辑框获失去焦点
EN_MAXTEX; 超出了规定的最大字符就会发出消息
EN_SETFOCUS; 获得焦点
EN_UPDATE; 在编辑框准备显示改变了正文时发送该消息
EN_VSCROLL; 用户在垂直滚动条上单击鼠标
10.只读消息
EM_SETREADONLY; 只读消息,用法: SendMessage(hEdit1, EM_SETREADONLY, 1, 0);
11.屏蔽系统右键菜单(重写回调函数)
LONG_PTR oldProc;//保存旧的回调函数地址
//在初始消息中重新设置Edit控件的回调函数
BOOL MyWinDialog::OnInitDialog(WPARAM wParam, LPARAM lParam)
{
AfxCWin::OnInitDialog(wParam, lParam);
//TODO:初始化代码
HWND hEditWnd = ::GetDlgItem(m_hWnd, IDC_EDIT2);
//重新设置Edit控件的回调函数
oldProc = SetWindowLongPtr(hEditWnd, GWLP_WNDPROC, (LONG_PTR)EditProc);
}
//新的回调函数
LONG_PTR CALLBACK EditProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_RBUTTONDOWN:
{
//添加自己的右键菜单,如果不添加直接返回1就能屏蔽掉系统菜单了
HMENU hSub = GetSubMenu(pMyDlg->EditMenu, 0);
POINT pt;
GetCursorPos(&pt);
TrackPopupMenu(hSub, TPM_LEFTBUTTON | TPM_TOPALIGN | TPM_RIGHTBUTTON,pt.x, pt.y, 0,pMyDlg->GetHwnd(), NULL);
}
return 1;
default:
break;
}
//返回旧的回调函数
return CallWindowProc((WNDPROC)oldProc, hWnd, uMsg, wParam, lParam);
}
12.动态创建控件
//Edit控件的创建
HWND hEdit1 = 0;
HWND hEdit2 = 0;
//创建单行控件
hEdit1 = ::CreateWindowW(TEXT("Edit"), TEXT("Edit Control1"),
WS_CHILD|WS_VISIBLE|ES_LEFT,
200, 20, 100, 20, hWnd, (HMENU)10001, g_hInstance, NULL);//单行文本
//创建多行控件
hEdit2 = ::CreateWindow(TEXT("Edit"), TEXT("Edit Control2\r\n多行文本控件"), WS_CHILD | WS_VISIBLE | ES_LEFT | ES_MULTILINE | ES_WANTRETURN | WS_VSCROLL | ES_AUTOVSCROLL,
250, 50, 150, 80, hWnd, (HMENU)10002, g_hInstance, NULL);