An edit control in Microsoft Windows lets you type in a word or number. You probably also want an OK button for the user to press after typing in the word or number. How to Create a Single Line Edit Control.
Untitled1.rc
.
Put the following into it.
//#include "resource.h" #include "windows.h" #include "winuser.h" #include "windef.h" //My window contains an edit control. #define IDD_MYWINDOW 1 #define IDC_MYEDITCONTROL 2 #ifndef IDC_STATIC #define IDC_STATIC (-1) #endif IDD_MYWINDOW DIALOGEX 0, 0, 169, 82 STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU CAPTION "This is my window." FONT 8, "MS Sans Serif", 0, 0, 0x0 BEGIN GROUPBOX "Please input an integer.", IDC_STATIC, 10, 10, 150, 60 LTEXT "The integer:", IDC_STATIC, 15, 20,70,8 EDITTEXT IDC_MYEDITCONTROL, 15, 30, 44, 12, ES_AUTOHSCROLL DEFPUSHBUTTON "OK", IDOK, 15, 48, 50, 14 END
main.cpp
file,
before including
windows.h
,
insert the following.
#include <sstream> //for classes istringstream and ostringstream using namespace std;
main.cpp
after including
windows.h
.
#define IDD_MYWINDOW 1 #define IDC_MYEDITCONTROL 2
WinMain
function in
main.cpp
immediately after the call to
ShowWindow
.
CreateDialog( hThisInstance, MAKEINTRESOURCE(IDD_MYWINDOW), hwnd, myDialogProc );
WinMain
function.
static INT_PTR CALLBACK myDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: switch(wParam) { case IDOK: { const size_t n = 12; //number of characters TCHAR lpszInteger[n]; //Get number of characters. const WORD cchInteger = SendDlgItemMessage(hDlg, IDC_MYEDITCONTROL, EM_LINELENGTH, static_cast<WPARAM>(0), static_cast<LPARAM>(0) ); if (cchInteger >= n) { MessageBox(hDlg, "Too many characters.", "Error", MB_OK); EndDialog(hDlg, TRUE); return FALSE; } if (cchInteger == 0) { MessageBox(hDlg, "No characters entered.", "Error", MB_OK); EndDialog(hDlg, TRUE); return FALSE; } //Put the number of characters into 1st word of buffer. *reinterpret_cast<LPWORD>(lpszInteger) = cchInteger; //Get the characters. SendDlgItemMessage( hDlg, IDC_MYEDITCONTROL, EM_GETLINE, static_cast<WPARAM>(0), //line 0 reinterpret_cast<LPARAM>(lpszInteger) ); //Null-terminate the string. lpszInteger[cchInteger] = '\0'; //Convert the string of characters to an integer. const string s(lpszInteger); istringstream ist(s); int i; //uninitialized variable ist >> i; ++i; //Perform arithmetic on the integer. ostringstream ost; ost << i; MessageBox(hDlg, ost.str().c_str(), "Added 1:", MB_OK); EndDialog(hDlg, TRUE); return TRUE; } case IDCANCEL: EndDialog(hDlg, TRUE); return TRUE; default:; } default:; } return FALSE; UNREFERENCED_PARAMETER(lParam); }