CnCrypt代码 之 限制只能输入数字的文本框

LRESULT CALLBACK NumberFieldProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    WNDPROC wp = (WNDPROC)GetWindowLongPtr(hWnd, GWLP_USERDATA);

    switch (message)
    {
    case WM_PASTE:
        return 1;
    case WM_CONTEXTMENU:
        return 1;
    case WM_CHAR:
    {
        char nChar = (char)wParam;
        BOOL bConitue = (nChar >= '0' && nChar <= '9')
            || nChar == '.'
            || nChar == 8;
        if (!bConitue)
        {
            return 1;
        }

        WCHAR szOldPassword[128];
        GetWindowText(hWnd, szOldPassword, ARRAYSIZE(szOldPassword));
        DWORD dwOldSel = Edit_GetSel(hWnd);
        LRESULT lResult = CallWindowProc(wp, hWnd, message, wParam, lParam);
        WCHAR szNewPassword[128];
        GetWindowText(hWnd, szNewPassword, ARRAYSIZE(szNewPassword));
        WCHAR * lpPos = wcsstr(szNewPassword, L".");
        // 如果点在第一位,或者多于一个点,或者小数点多于两位。
        if (lpPos != NULL && (lpPos == szNewPassword || wcsstr(lpPos + 1, L".") !=NULL || wcslen(lpPos) > 3))
        {
            SetWindowText(hWnd, szOldPassword);
            Edit_SetSel(hWnd, HIWORD(dwOldSel), LOWORD(dwOldSel));
        }
        return lResult;
    }
    }

    return CallWindowProc(wp, hWnd, message, wParam, lParam);
}

void    ToNumberField(HWND hwndCtrl)
{
    ::SendMessage(hwndCtrl, EM_LIMITTEXT, 12, 0);
    SetWindowLongPtr(hwndCtrl, GWLP_USERDATA, (LONG_PTR)GetWindowLongPtr(hwndCtrl, GWLP_WNDPROC));
    SetWindowLongPtr(hwndCtrl, GWLP_WNDPROC, (LONG_PTR)NumberFieldProc);
}

你可能感兴趣的:(CnCrypt)