首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC++

VC++ 開發必備常用代碼片段速查手冊

     編輯:VC++

1. 獲取系統時間 (GetLocalTime)

CString sTime, sYear, sMonth, sDay;
SYSTEMTIME CurTime;
GetLocalTime(&CurTime);
sYear.Format(_T("%d年"), CurTime.wYear);
sMonth.Format(_T("%d月"), CurTime.wMonth);
sDay.Format(_T("%d日"), CurTime.wDay);
sTime = sYear + sMonth + sDay;
// CurTime.wHour, wMinute, wSecond 同理
AfxMessageBox(sTime);

2. 十六進制字符串轉字節數組

CString str = _T("4d3f0a2278");
unsigned char a[12];
long x;
for (int i = 0; i < str.GetLength() / 2; i++) {
    swscanf_s(str.Mid(2*i, 2), _T("%x"), &x);
    a[i] = (unsigned char)x;
}

3. 獲取當前工作目錄

TCHAR CurPath[MAX_PATH];
DWORD size = MAX_PATH;
GetCurrentDirectory(size, CurPath);
AfxMessageBox(CurPath);

4. 獲取系統目錄

TCHAR SysPath[MAX_PATH];
GetSystemDirectory(SysPath, MAX_PATH);
AfxMessageBox(SysPath);

5. 從字符串提取純數字

CString GetStr(const CString& str) {
    CString res;
    for (int i = 0; i < str.GetLength(); i++) {
        TCHAR ch = str[i];
        if (ch >= _T('0') && ch <= _T('9')) res += ch;
    }
    return res;
}
// 用法
CString strNum = GetStr(_T("測試125各國87kk")); // 返回 "12587"

6. 創建無模態對話框

CDlg_Test* pDlg = new CDlg_Test;
pDlg->Create(IDD_DIALOG1, this);
pDlg->ShowWindow(SW_SHOW);
// 注意:需在對話框類中重載 PostNcDestroy 刪除 this
// void CDlg_Test::PostNcDestroy() { delete this; }

7. 獲取窗口屏幕絕對座標

CRect rect;
GetClientRect(&rect);     // 客戶區座標 (相對窗口)
ClientToScreen(&rect);    // 轉換為屏幕座標
CString str;
str.Format(_T("左上角屏幕座標: (%d, %d)"), rect.left, rect.top);
AfxMessageBox(str);

8. 複製整個文件夾 (SHFileOperation)

SHFILEOPSTRUCT Op = {0};
Op.hwnd = NULL;
Op.wFunc = FO_COPY;
Op.pFrom = _T("E:\\temp\0");          // 雙\0結尾
Op.pTo = _T("\\\\Server\\Share\\Target\0");
Op.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION;
Op.fAnyOperationsAborted = FALSE;

if (SHFileOperation(&Op) == 0)
    MessageBox(_T("複製完成"), _T("提示"), MB_OK | MB_ICONINFORMATION);

9. 捕獲 Ctrl + 左鍵 組合鍵

// 在窗口過程或 OnLButtonDown 中
case WM_LBUTTONDOWN:
    if (wParam & MK_CONTROL) // 或 GetKeyState(VK_CONTROL) < 0
        MessageBox(_T("Ctrl+左鍵被按下"));
    break;

10. 獲取編輯控件第一行文本

CString lineText;
int len = LineLength(LineIndex(0));
LPTSTR pBuf = lineText.GetBuffer(len);
GetLine(0, pBuf, len);
lineText.ReleaseBuffer();
AfxMessageBox(lineText);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved