MFC控件 Edit,控制只能輸入數字和小數點


照抄這個的

MFC實現Edit輸入限制(只允許輸入數字,小數點)

 

Edit 控件的屬性Number,只能控制只輸入數字,不能控制輸入小數的情況,實現這個就繼承CEdit來寫新的類

.h 代碼

 1 #pragma once
 2 
 3 // CEditEx
 4 
 5 class CEditEx : public CEdit
 6 {
 7     DECLARE_DYNAMIC(CEditEx)
 8 
 9 public:
10     CEditEx();
11     virtual ~CEditEx();
12 
13 protected:
14     DECLARE_MESSAGE_MAP()
15 public:
16     afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
17     afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
18 };

.cpp

 1 // EditEx.cpp : 實現文件
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "CEditEx.h"
 6 
 7 // CEditEx
 8 
 9 IMPLEMENT_DYNAMIC(CEditEx, CEdit)
10 
11 CEditEx::CEditEx()
12 {
13 }
14 
15 CEditEx::~CEditEx()
16 {
17 }
18 
19 BEGIN_MESSAGE_MAP(CEditEx, CEdit)
20     ON_WM_CHAR()
21     ON_WM_KEYUP()
22 END_MESSAGE_MAP()
23 
24 // CEditEx 消息處理程序
25 void CEditEx::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
26 {
27     // TODO:  在此添加消息處理程序代碼和/或調用默認值
28 
29     // 處理小數點
30     if (nChar == '.') 
31     {
32         CString str;
33         GetWindowText(str);
34 
35         // 限制第一位為小數
36         if (str.GetLength() == 0) 
37         {
38             // 第一位輸入小數點
39             MessageBox(_T("第一位不可以是小數點"));
40             return;
41         }
42         // 限制只允許有一個小數點
43         if (str.Find('.') == -1) 
44         {
45             CEdit::OnChar(nChar, nRepCnt, nFlags);
46         }
47         else 
48         {
49             if (str[0] == '.')
50             {
51                 SetWindowText(str.Mid(1, str.GetLength()));
52                 MessageBox(_T("第一位不可以是小數點"));
53             }
54             // 小數點出現第二次
55             MessageBox(_T("小數點只能輸入一次"));
56         }
57     }
58     // 數理數字和退格鍵
59     else if ((nChar >= '0' && nChar <= '9') || nChar == 0x08)
60     {
61         CEdit::OnChar(nChar, nRepCnt, nFlags);
62     }
63     else 
64     {
65         // 出現非數字鍵,退格鍵
66         MessageBox(_T("只能輸入數字,退格鍵"));
67     }
68 }
69 
70 // 修復先輸入數字之后,可以在第一位輸入小數點
71 void CEditEx::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
72 {
73     // TODO: 在此添加消息處理程序代碼和/或調用默認值
74     if (nChar == VK_DECIMAL || nChar == VK_OEM_PERIOD) {
75         CString str;
76         GetWindowText(str);
77         if (str[0] == '.') {
78             SetWindowText(str.Mid(1, str.GetLength()));
79             MessageBox(_T("第一位不可以是小數點"));
80         }
81     }
82     CEdit::OnKeyUp(nChar, nRepCnt, nFlags);
83 
84 }

這個代碼有個bug,第二次輸入 . 時提示 “小數點只能輸一次”,這個沒問題,但第三次輸入 . 時,提示 “只能輸入小數,退格鍵”

是不是第二次輸入的小數點沒有處理,第三次輸入后nChar的值就不是輸入的值了,但不影響功能,就不改了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM