/* _____________________________________________________________________________________ I N T R O D U C T I O N T O K E Y H A N D L E R S C++/CLI Version R. Kessler ____________________________________________________________________________________ Updated 11/3/2014 1.This shows how to validate data in a textbox. Use the Keydown event to test the keys. 2. Then use the keypress event to tell O/S whether to accept key or not Events fire in this order: KeyDown, KeyPress, KeyUp. KeyDown intercepts characters from the keyboard. KeyPress can be used to keep characters from entering the control!!! */ static bool IsValidChar = false; //use this to decide if a character is what we want static String^ MSGTITLE = "Welcome to Ron's Store"; private: System::Void txtFirst_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) { //---make this handler to examine which key is pressed. A-Z or space, or backspace if ((e->KeyCode >=Keys::A && e->KeyCode <= Keys::Z) | (e->KeyCode == Keys::Space | e->KeyCode == Keys::Back)) IsValidChar = true; else IsValidChar = false; } private: System::Void txtFirst_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) { //This of Handled as "Blocked" if(IsValidChar ==true) e->Handled = false; //means the control can process the char (Don't Block) else { e->Handled = true; //stop char from being sent to control (Block it) } } private: System::Void txtQuantity_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) { //---make this handler to examine which key is pressed. 1-9 or space, or backspace if ((e->KeyCode >=Keys::D1 && e->KeyCode <= Keys::D9) | (e->KeyCode == Keys::Space | e->KeyCode == Keys::Back) | e->KeyCode == Keys::OemPeriod) //any "." in any language/region. OEM means "original equipment manufacturer" IsValidChar = true; else IsValidChar = false; } private: System::Void txtQuantity_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) { if(IsValidChar ==true) e->Handled = false; //don't block else { e->Handled = true; //block it } } private: System::Void btnOK_Click(System::Object^ sender, System::EventArgs^ e) { if(txtQuantity->Text !="" && txtFirst->Text !="") IsValidChar = true; else IsValidChar = false; //---display the result switch (IsValidChar) { case true: ShowMsg("Data is valid."); break; case false: ShowMsg("Data is not valid."); break; default: ShowMsg("Please enter all data."); break; } } private: void ShowMsg(String^ msg) { //---show the message boxes from here MessageBox::Show(msg, MSGTITLE, MessageBoxButtons::OK, MessageBoxIcon::Information); }