Window中VB有InputBox的功能,但SDK、MFC、WTL等并未提供类似功能。
WTL有CIndirectDialogImpl,可以很简单的构建对话框。基于此,实现一个简单的InputBox功能
#define BUF_LEN MAX_PATH #define IDC_TEXT (100) class CInputBox: public CIndirectDialogImpl< CInputBox > { private: LPCTSTR szPrompt_; LPCTSTR szTitle_; LPCTSTR szDefaultText_; TCHAR strResult[BUF_LEN]; public: BEGIN_DIALOG(0, 0, 257, 62) DIALOG_CAPTION(szTitle_ != nullptr ? szTitle_ : _T("")) DIALOG_STYLE(DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU) DIALOG_FONT(9, _T("SimSun")) END_DIALOG() BEGIN_CONTROLS_MAP() CONTROL_DEFPUSHBUTTON(_T("OK"), IDOK, 200, 11, 50, 14, 0, 0) CONTROL_PUSHBUTTON(_T("Cancel"), IDCANCEL, 200, 31, 50, 14, 0, 0) CONTROL_LTEXT(szPrompt_ != nullptr ? szPrompt_ : _T("Please input: "), IDC_STATIC, 7, 7, 158, 14, 0, 0) CONTROL_EDITTEXT(IDC_TEXT, 7, 31, 180, 14, 0, 0) END_CONTROLS_MAP() BEGIN_MSG_MAP(CInputBox) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnCloseCmd) COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd) END_MSG_MAP() CInputBox::CInputBox() : szPrompt_(nullptr), szTitle_(nullptr), szDefaultText_(nullptr){ memset(strResult, 0, sizeof(TCHAR)*BUF_LEN); } static bool InputBox(LPCTSTR szPrompt, LPTSTR strResult, LPCTSTR szTitle = _T(""), LPCTSTR szDefaultText = _T(""), HWND hParent = nullptr){ CInputBox dlg; dlg.szPrompt_ = szPrompt; dlg.szTitle_ = szTitle; dlg.szDefaultText_ = szDefaultText; if (IDOK == dlg.DoModal(hParent)) { // get return string. lstrcpyn(strResult, dlg.strResult, BUF_LEN); return true; } return false; } LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { CenterWindow(GetParent()); if (szDefaultText_) { ::SetWindowText(::GetDlgItem(m_hWnd, IDC_TEXT), szDefaultText_); } // set focus to edit control item. ::SetFocus(::GetDlgItem(m_hWnd, IDC_TEXT)); // return false to prevent setfocus in dialogproc. return false; } LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { if (wID == IDOK) { ::GetWindowText(::GetDlgItem(m_hWnd, IDC_TEXT), strResult, BUF_LEN - 1); } EndDialog(wID); return 0; } };
使用类似于如下:
void demo() { TCHAR strPassWd[MAX_PATH]; if (CInputBox::InputBox(_T("请输入加密密码:"), strPassWd, _T("输入密码"))) { // } return ; }