当前位置:   article > 正文

MFC实现Edit输入限制(只允许输入数字,负号和小数点)_mfc编辑框限制数字和小数

mfc编辑框限制数字和小数

  1)添加个C++类 eg. class Dot:public CEdit

 

  2)给这个类添加onChar()消息

 

  afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);

 

  3)*.cpp中

void Dot::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
 // TODO: Add your message handler code here and/or call default
 // 保证小数点最多只能出现一次
 if(nChar=='.')
 {
    CString str;
    // 获取原来编辑框中的字符串
     GetWindowText(str);
     //若原来的字符串中已经有一个小数点,则不将小数点输入,保证了最多只能输入一个小数点
    if(str.Find('.')!=-1)
    {
    }
    // 否则就输入这个小数点
   else
   {
      CEdit::OnChar(nChar, nRepCnt, nFlags); 
    }
 }
 // 保证负号只能出现一次,并且只能出现在第一个字符
 else if(nChar=='-')
 {
    CString str;
  GetWindowText(str);
  // 还没有输入任何字符串
  if(str.IsEmpty())
  {
   CEdit::OnChar(nChar, nRepCnt, nFlags); 
  }
  else
  {
   int nSource,nDestination;
   GetSel(nSource,nDestination);
   // 此时选择了全部的内容
   if(nSource==0&&nDestination==str.GetLength())
   {
    CEdit::OnChar(nChar, nRepCnt, nFlags); 
   }
   else
   {
   
   
 }
 // 除了小数点和负号,还允许输入数字,Backspace,Delete
 else if((nChar>='0' && nChar<='9')||(nChar==0x08)||(nChar==0x10))
 {
  CEdit::OnChar(nChar, nRepCnt, nFlags); 
 }
 // 其它的键,都不响应
 else
 {
 }
}

 

4)在*Dlg.h加上

----》#include"Dot.h"

----》Dot  m_s;

 

5)在*Dlg.cpp加上

-----》DDX_Control(pDX, IDC_EDIT1, m_s);

 





或者


  1. BOOL CWeiXinQ::PreTranslateMessage(MSG* pMsg)
  2. {
  3. // TODO: 在此添加专用代码和/或调用基类
  4. //指定对话框只接受数字按键输入,其他符号输入无效
  5. //获取控件窗口指针
  6. CEdit* pEdit1 = (CEdit*)GetDlgItem(IDC_EDIT1_Q_MONEY);
  7. CEdit* pEdit2 = (CEdit*)GetDlgItem(IDC_EDIT2_Q_CODE);
  8. if( (GetFocus() == pEdit1 ||GetFocus() == pEdit2) && (pMsg->message == WM_CHAR) )
  9. {
  10. //只允许输入数字和小数点“.”
  11. if((pMsg->wParam <= '9' && pMsg->wParam >= '0') || pMsg->wParam == '.')
  12. {
  13. //金额输入框只允许输入一个小数点
  14. if(pMsg->wParam == '.')
  15. {
  16. CString str;
  17. int nPos = 0;
  18. GetDlgItemText(IDC_EDIT1_Q_MONEY, str); // 获取edit中文本
  19. nPos = str.Find('.'); // 查找.的位置
  20. if(nPos >= 0)
  21. {
  22. return 1;
  23. }
  24. }
  25. return 0;
  26. }
  27. else if(pMsg->wParam == 0x08 || pMsg->wParam == 0x10) //接受Backspace和delete键
  28. {
  29. return 0;
  30. }
  31. else
  32. {
  33. //响应标签页切换的快捷键
  34. switch(pMsg->wParam)
  35. {
  36. case 'q':
  37. case 'Q':
  38. case 'w':
  39. case 'W':
  40. case 'e':
  41. case 'E':
  42. case 'r':
  43. case 'R':
  44. case 't':
  45. case 'T':
  46. case 'y':
  47. case 'Y':
  48. case 'u':
  49. case 'U':
  50. case 'i':
  51. case 'I':
  52. case 'o':
  53. case 'O':
  54. CWnd *pParent = GetParent();
  55. pParent->SetFocus();
  56. }
  57. return 1;
  58. }
  59. }
  60. return CDialogEx::PreTranslateMessage(pMsg);
  61. }



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/83022
推荐阅读
相关标签
  

闽ICP备14008679号