整理 8 個 VC++ 開發中極高頻率用到的實用技巧,涵蓋系統時間、字串解析、目錄操作、檔案複製、對話框建立、座標轉換、鍵盤組合鍵偵測,方便隨時查閱複製。
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);
CString str = _T("4d3f0a2278");
BYTE a[12];
long x;
for (int i = 0; i < str.GetLength() / 2; i++) {
swscanf(str.Mid(2*i, 2), _T("%x"), &x);
a[i] = (BYTE)x;
}
// 目前工作目錄
char CurPath[MAX_PATH];
DWORD dwSize = MAX_PATH;
GetCurrentDirectory(dwSize, CurPath);
AfxMessageBox(CurPath);
// 系統目錄
char SysPath[MAX_PATH];
GetSystemDirectory(SysPath, MAX_PATH);
AfxMessageBox(SysPath);
CString GetStr(CString str)
{
CString strNum;
for (int i = 0; i < str.GetLength(); i++) {
TCHAR ch = str.GetAt(i);
if (ch >= _T('0') && ch <= _T('9'))
strNum += ch;
}
return strNum;
}
// 使用
CString str(_T("測試125各國87kk"));
AfxMessageBox(GetStr(str)); // 輸出 12587
CDlg_Test* pDlg = new CDlg_Test;
pDlg->Create(IDD_DIALOG1, this);
pDlg->ShowWindow(SW_SHOW);
// 記得在適當時機 delete pDlg 避免記憶體洩漏
CRect rect;
GetClientRect(&rect); // 客戶區座標 (相對視窗左上角)
ClientToScreen(&rect); // 轉換為螢幕絕對座標
CString str;
str.Format(_T("Left: %d, Top: %d, Right: %d, Bottom: %d"),
rect.left, rect.top, rect.right, rect.bottom);
AfxMessageBox(str);
SHFILEOPSTRUCT Op = {0};
Op.hwnd = NULL;
Op.wFunc = FO_COPY;
Op.pFrom = _T("E:\\temp\0"); // 雙重結尾 \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);
關鍵:pFrom/pTo 必須以雙重空字元結尾(\0\0),路徑間可用單一 \0 分隔多個來源。
// 視窗程序中
case WM_LBUTTONDOWN:
if (wParam & MK_CONTROL) // 或 GetKeyState(VK_CONTROL) < 0
MessageBox(hwnd, _T("Ctrl+左鍵"), _T("提示"), MB_OK);
break;
這 8 個技巧涵蓋了 VC++ 開發 80% 以上的常見需求。建議收藏備查,下次需要時直接複製修改即可。