1. Trang chủ
  2. » Công Nghệ Thông Tin

EBOOK lập trình MFC bài tập áp dụng

132 508 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 132
Dung lượng 2,86 MB

Nội dung

Giáo trình lập trình MFC chứa các bài toán căn bản giúp mọi người học và code tốt. Biến đổi kiểu dự liệu Sử dụng các control trong MFC Sử dụng trace icon Đúc kết nhiều kỹ thuật và áp dụng nhiều thuật toán

Mục lục 1. Chuyển đổi chuỗi : http://www.convertdatatypes.com/Convert-long-to-char-Array-in-C.html ......... 3 2. Ẩn Control - Invisible ......................................................................................................................... 3 3. Ẩn Control – MFC: enable and disable a control ............................................................................ 3 4. Ẩn các control trong group ................................................................................................................ 4 5. RegEdit................................................................................................................................................. 7 6. Convert................................................................................................................................................. 9 1. 6.1 char * to string ............................................................................................................................ 9 6.2 string to char * ............................................................................................................................ 9 6.3 Convert char * to LPWSTR ....................................................................................................... 9 6.4 Convert char * to wchar_t........................................................................................................ 10 6.5 CString  char *...................................................................................................................... 10 6.6 Int  char * .............................................................................................................................. 10 6.7 Char *  int ............................................................................................................................. 10 6.8 string *  int ............................................................................................................................ 10 6.9 string *  wchar_t ................................................................................................................... 10 6.10 int *  wchar_t ........................................................................................................................ 11 6.11 string *  CString ................................................................................................................... 11 6.12 Cstring *  string .................................................................................................................... 11 6.13 wchar_t*  char * ................................................................................................................... 11 6.14 Convert wchar_t* to int in C ................................................................................................... 11 6.15 wstring  int ........................................................................................................................... 11 6.16 CString to std::wstring: ............................................................................................................ 12 6.17 wstring to std::CString: ............................................................................................................ 12 6.18 String to Wstring....................................................................................................................... 12 6.19 Wstring to String....................................................................................................................... 12 System ................................................................................................................................................ 13 1.1 Remove file ................................................................................................................................ 13 1.2 Copy file ..................................................................................................................................... 13 1.3 Run file .exe ............................................................................................................................... 13 1.4 Move file..................................................................................................................................... 13 1.5 Open file ..................................................................................................................................... 14 1.6 Lấy dữ liệu từ màn hình console – Lấy kết quả thực thi câu lệnh trong cmd ..................... 14 1 2. Malloc ................................................................................................................................................. 14 3. Memset(), memcpy(), memcmp() .......................................................................................... 14 4. ERROR .............................................................................................................................................. 17 5. Split..................................................................................................................................................... 17 6. Create File.......................................................................................................................................... 18 7. Create & Start Service ...................................................................................................................... 18 8. C++: Run program as administrator .............................................................................................. 19 9. Đường dẫn tương đối trong C/C++ ................................................................................................. 20 10. File .................................................................................................................................................. 21 10.1 Get length................................................................................................................................... 21 10.2 Create file hiden ........................................................................................................................ 21 10.3 Write file .................................................................................................................................... 22 10.4 Read full data ............................................................................................................................ 24 10.5 Process byte data ....................................................................................................................... 24 10.6 Check file exist........................................................................................................................... 25 10.7 Get file Name ............................................................................................................................. 26 10.8 Find string in string .................................................................................................................. 26 10.9 Read & Write file Tiếng Nhật .................................................................................................. 26 10.10 Read file font tiếng nhật đọc theo từng dòng wchar_t ....................................................... 27 10.11 Replace ................................................................................................................................... 28 10.12 Get Date ................................................................................................................................. 28 11. Get user my computer .................................................................................................................. 29 12. Close X in MFC ............................................................................................................................. 30 13. Get all status letter ........................................................................................................................ 30 14. MFC UI .......................................................................................................................................... 32 14.1 Close X ....................................................................................................................................... 32 14.2 Cắt chuỗi trong CSTRING....................................................................................................... 34 14.3 Compare CString ................................................................................................................... 46 14.4 Write debug plog ....................................................................................................................... 47 14.5 Progress bar............................................................................................................................... 47 14.6 Circle bar ................................................................................................................................... 48 14.7 Set value for control ................................................................................................................ 110 14.8 Lấy Vị trí và giá trị trong combobox..................................................................................... 110 2 Check đường dẫn tồn tại ........................................................................................................ 111 14.9 14.10 Truyền dữ liệu giữa 2 app thông qua tên app .................................................................. 111 14.11 Close Dialog ......................................................................................................................... 113 14.12 Set window Top ................................................................................................................... 113 14.13 Chuyển thư mục thực thi lênh command line .................................................................. 114 14.14 Run cmd không hiển thị màn hình đen ............................................................................. 114 14.15 Lấy ngày giờ khi buld project ............................................................................................ 115 14.16 Show Message ...................................................................................................................... 117 14.17 Xóa Icon trong Cache ......................................................................................................... 117 14.18 Mutex ................................................................................................................................... 118 15. Định nghĩa rồi không cần định nghĩa lại................................................................................... 118 16. Build MFC release ...................................................................................................................... 118 1. Chuyển đổi chuỗi : http://www.convertdatatypes.com/Convert-long-to-char-Array-inC.html 2. Ẩn Control - Invisible IDC_YOURCTRLID : ID control của bạn BEGIN CODE : GetDlgItem(IDC_YOURCTRLID)->ShowWindow(SW_HIDE) 3. Ẩn Control – MFC: enable and disable a control IDC_YOURCTRLID : ID control của bạn BEGIN CODE CWnd *wnd = this->GetDlgItem(IDC_YOURCTRLID); //Which control to disable, in this case the "OK" button if (wnd->IsWindowEnabled()) wnd->EnableWindow(FALSE); else wnd->EnableWindow(TRUE); 3 4. Ẩn các control trong group Sử dụng class group - Header Files: tạo class EnableGroupboxControls.h // EnableGroupboxControls.h Version 1.0 - see article at CodeProject.com // // Author: Hans Dietrich // hdietrich@gmail.com // // License: // This software is released under the Code Project Open License (CPOL), // which may be found here: http://www.codeproject.com/info/eula.aspx // You are free to use this software in any way you like, except that you // may not sell this source code. // // This software is provided "as is" with no expressed or implied warranty. // I accept no liability for any damage or loss of business that this // software may cause. // /////////////////////////////////////////////////////////////////////////////// #ifndef ENABLEGROUPBOXCONTROLS_H #define ENABLEGROUPBOXCONTROLS_H int EnableGroupboxControls(HWND hWnd, BOOL bEnable); 4 #endif //ENABLEGROUPBOXCONTROLS_H - Source Files : tạo class : EnableGroupboxControls.cpp // EnableGroupboxControls.cpp Version 1.0 - see article at CodeProject.com // // Author: Hans Dietrich // hdietrich@gmail.com // // Description: // The EnableGroupboxControls function enables or disables all the controls // contained within a groupbox. // // History // Version 1.0 - 2008 April 9 // - Initial public release // // License: // This software is released under the Code Project Open License (CPOL), // which may be found here: http://www.codeproject.com/info/eula.aspx // You are free to use this software in any way you like, except that you // may not sell this source code. // // This software is provided "as is" with no expressed or implied warranty. // I accept no liability for any damage or loss of business that this // software may cause. // /////////////////////////////////////////////////////////////////////////////// #include "windows.h" #include "tchar.h" #include "EnableGroupboxControls.h" //==================================================================== ========= // // EnableGroupboxControls() // // Purpose: This function enables/disables all the controls that are // completely contained with a groupbox. // // Parameters: hWnd - HWND of groupbox control // bEnable - TRUE = enable controls within groupbox // 5 // Returns: int - number of controls enabled/disabled. If zero is // returned, it means that no controls lie within the // rect of the groupbox. // int EnableGroupboxControls(HWND hWnd, BOOL bEnable) { int rc = 0; if (::IsWindow(hWnd)) { // get class name TCHAR szClassName[MAX_PATH]; szClassName[0] = _T('\0'); ::GetClassName(hWnd, szClassName, sizeof(szClassName)/sizeof(TCHAR)-2); // get window style LONG lStyle = ::GetWindowLong(hWnd, GWL_STYLE); if ((_tcsicmp(szClassName, _T("Button")) == 0) && ((lStyle & BS_GROUPBOX) == BS_GROUPBOX)) { // this is a groupbox RECT rectGroupbox; ::GetWindowRect(hWnd, &rectGroupbox); // get first child control HWND hWndChild = 0; HWND hWndParent = ::GetParent(hWnd); if (IsWindow(hWndParent)) hWndChild = ::GetWindow(hWndParent, GW_CHILD); while (hWndChild) { RECT rectChild; ::GetWindowRect(hWndChild, &rectChild); // check if child rect is entirely contained within groupbox if ((rectChild.left >= rectGroupbox.left) && (rectChild.right = rectGroupbox.top) && (rectChild.bottom m_wWidth; m_PictureSize.cy = m_pGIFLSDescriptor>m_wHeight; // determine frame count for this picture 70 UINT nFrameCount=0; ResetDataPointer(); while (SkipNextGraphicBlock()) nFrameCount++; #ifdef GIF_TRACING TRACE( _T(" -= GIF encountered\n" "Logical Screen dimensions = %dx%d\n" "Global color table = %d\n" "Color depth = %d\n" "Sort flag = %d\n" "Size of Global Color Table = %d\n" "Background color index = %d\n" "Pixel aspect ratio = %d\n" "Frame count = %d\n" "Background color = %06Xh\n\n" ), m_pGIFLSDescriptor->m_wWidth, m_pGIFLSDescriptor->m_wHeight, m_pGIFLSDescriptor>GetPackedValue(LSD_PACKED_GLOBALCT), m_pGIFLSDescriptor>GetPackedValue(LSD_PACKED_CRESOLUTION), m_pGIFLSDescriptor>GetPackedValue(LSD_PACKED_SORT), m_pGIFLSDescriptor>GetPackedValue(LSD_PACKED_GLOBALCTSIZE), m_pGIFLSDescriptor->m_cBkIndex, m_pGIFLSDescriptor->m_cPixelAspect, 71 nFrameCount, m_clrBackground ); EnumGIFBlocks(); #endif if (nFrameCount == 0) // it's an empty GIF! { m_pRawData = NULL; GlobalUnlock(hGlobal); return FALSE; }; // now check the frame count // if there's only one frame, no need to animate this GIF // therefore, treat it like any other pic if (nFrameCount == 1) { // clear GIF variables m_pRawData = NULL; GlobalUnlock(hGlobal); // don't delete memory on object's release if (CreateStreamOnHGlobal(hGlobal,FALSE,&pStream) != S_OK) return FALSE; 72 if (OleLoadPicture(pStream,dwSize,FALSE,IID_IPicture, (LPVOID *)&m_pPicture) != S_OK) { pStream->Release(); return FALSE; }; pStream->Release(); } else { // if, on the contrary, there are several frames // then store separate frames in an array TFrame frame; UINT nBlockLen; HGLOBAL hFrameData; UINT nCurFrame = 0; ResetDataPointer(); while (hFrameData = GetNextGraphicBlock(&nBlockLen, &frame.m_nDelay, &frame.m_frameSize, &frame.m_frameOffset, &frame.m_nDisposal) ) { #ifdef GIF_TRACING 73 ////////////////////////////////////////////// // uncomment the following strings if you want // to write separate frames on disk // // CString szName; // szName.Format(_T("%.4d.gif"),nCurFrame); // WriteDataOnDisk(szName,hFrameData,nBlockLen); // nCurFrame++; #endif // GIF_TRACING IStream *pStream = NULL; // delete memory on object's release if (CreateStreamOnHGlobal(hFrameData,TRUE,&pStream) != S_OK) { GlobalFree(hFrameData); continue; }; if (OleLoadPicture(pStream,nBlockLen,FALSE, IID_IPicture, reinterpret_cast(&frame.m_pPicture)) != S_OK) { pStream->Release(); 74 continue; }; pStream->Release(); // everything went well, add this frame m_arrFrames.push_back(frame); }; // clean after ourselves m_pRawData = NULL; GlobalUnlock(hGlobal); if (m_arrFrames.empty()) // couldn't load any frames return FALSE; }; }; // if (!IsGIF... return PrepareDC(m_PictureSize.cx,m_PictureSize.cy); } void CPictureEx::UnLoad() { Stop(); if (m_pPicture) { m_pPicture->Release(); m_pPicture = NULL; 75 }; std::vector::iterator it; for (it=m_arrFrames.begin();itRelease(); m_arrFrames.clear(); if (m_hMemDC) { SelectObject(m_hMemDC,m_hOldBitmap); ::DeleteDC(m_hMemDC); ::DeleteObject(m_hBitmap); m_hMemDC = NULL; m_hBitmap = NULL; }; if (m_hDispMemDC) { SelectObject(m_hDispMemDC,m_hDispOldBM); ::DeleteDC(m_hDispMemDC); ::DeleteObject(m_hDispMemBM); m_hDispMemDC = NULL; m_hDispMemBM = NULL; }; SetRect(&m_PaintRect,0,0,0,0); m_pGIFLSDescriptor = NULL; m_pGIFHeader 76 = NULL; m_pRawData = NULL; m_hThread = NULL; m_bIsInitialized = FALSE; m_bExitThread = FALSE; m_bIsGIF = FALSE; m_clrBackground = RGB(255,255,255); // white by default m_nGlobalCTSize = 0; m_nCurrOffset = 0; m_nCurrFrame = 0; m_nDataSize = 0; } BOOL CPictureEx::Draw() { if (!m_bIsInitialized) { TRACE(_T("Call one of the CPictureEx::Load() member functions before calling Draw()\n")); return FALSE; }; if (IsAnimatedGIF()) { // the picture needs animation // we'll start the thread that will handle it for us unsigned int nDummy; 77 m_hThread = (HANDLE) _beginthreadex(NULL,0,_ThreadAnimation,this, CREATE_SUSPENDED,&nDummy); if (!m_hThread) { TRACE(_T("Draw: Couldn't start a GIF animation thread\n")); return FALSE; } else ResumeThread(m_hThread); } else { if (m_pPicture) { long hmWidth; long hmHeight; m_pPicture->get_Width(&hmWidth); m_pPicture->get_Height(&hmHeight); if (m_pPicture->Render(m_hMemDC, 0, 0, m_PictureSize.cx, m_PictureSize.cy, 0, hmHeight, hmWidth, -hmHeight, NULL) == S_OK) { Invalidate(FALSE); return TRUE; }; }; }; 78 return FALSE; } SIZE CPictureEx::GetSize() const { return m_PictureSize; } BOOL CPictureEx::Load(LPCTSTR szFileName) { ASSERT(szFileName); CFile file; HGLOBAL hGlobal; DWORD dwSize; if (!file.Open(szFileName, CFile::modeRead | CFile::shareDenyWrite) ) { TRACE(_T("Load (file): Error opening file %s\n"),szFileName); return FALSE; }; dwSize = file.GetLength(); hGlobal = GlobalAlloc(GMEM_MOVEABLE | GMEM_NODISCARD,dwSize); 79 if (!hGlobal) { TRACE(_T("Load (file): Error allocating memory\n")); return FALSE; }; char *pData = reinterpret_cast(GlobalLock(hGlobal)); if (!pData) { TRACE(_T("Load (file): Error locking memory\n")); GlobalFree(hGlobal); return FALSE; }; TRY { file.Read(pData,dwSize); } CATCH(CFileException, e); { TRACE(_T("Load (file): An exception occured while reading the file %s\n"), szFileName); GlobalFree(hGlobal); e->Delete(); file.Close(); return FALSE; 80 } END_CATCH GlobalUnlock(hGlobal); file.Close(); BOOL bRetValue = Load(hGlobal,dwSize); GlobalFree(hGlobal); return bRetValue; } BOOL CPictureEx::Load(LPCTSTR szResourceName, LPCTSTR szResourceType) { ASSERT(szResourceName); ASSERT(szResourceType); HRSRC hPicture = FindResource(AfxGetResourceHandle(),szResourceName,szResourceType); HGLOBAL hResData; if (!hPicture || !(hResData = LoadResource(AfxGetResourceHandle(),hPicture))) { TRACE(_T("Load (resource): Error loading resource %s\n"),szResourceName); return FALSE; }; DWORD dwSize = SizeofResource(AfxGetResourceHandle(),hPicture); // hResData is not the real HGLOBAL (we can't lock it) // let's make it real 81 HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE | GMEM_NODISCARD,dwSize); if (!hGlobal) { TRACE(_T("Load (resource): Error allocating memory\n")); FreeResource(hResData); return FALSE; }; char *pDest = reinterpret_cast (GlobalLock(hGlobal)); char *pSrc = reinterpret_cast (LockResource(hResData)); if (!pSrc || !pDest) { TRACE(_T("Load (resource): Error locking memory\n")); GlobalFree(hGlobal); FreeResource(hResData); return FALSE; }; CopyMemory(pDest,pSrc,dwSize); FreeResource(hResData); GlobalUnlock(hGlobal); BOOL bRetValue = Load(hGlobal,dwSize); GlobalFree(hGlobal); return bRetValue; 82 } void CPictureEx::ResetDataPointer() { // skip header and logical screen descriptor m_nCurrOffset = sizeof(TGIFHeader)+sizeof(TGIFLSDescriptor)+m_nGlob alCTSize; } BOOL CPictureEx::SkipNextGraphicBlock() { if (!m_pRawData) return FALSE; // GIF header + LSDescriptor [+ GCT] [+ Control block] + Data enum GIFBlockTypes nBlock; nBlock = GetNextBlock(); while ((nBlock != BLOCK_CONTROLEXT) && (nBlock != BLOCK_IMAGE) && (nBlock != BLOCK_PLAINTEXT) && (nBlock != BLOCK_UNKNOWN) && (nBlock != BLOCK_TRAILER) ) { if (!SkipNextBlock()) return NULL; 83 nBlock = GetNextBlock(); }; if ((nBlock == BLOCK_UNKNOWN) || (nBlock == BLOCK_TRAILER)) return FALSE; // it's either a control ext.block, an image or a plain text if (GetNextBlockLen() 0) return sizeof(TGIFAppExtension)+nTmp; break; case BLOCK_COMMEXT: nTmp = GetSubBlocksLen(m_nCurrOffset+sizeof(TGIFCommentExt)); if (nTmp > 0) return sizeof(TGIFCommentExt)+nTmp; break; case BLOCK_CONTROLEXT: return sizeof(TGIFControlExt); break; 88 case BLOCK_PLAINTEXT: nTmp = GetSubBlocksLen(m_nCurrOffset+sizeof(TGIFPlainTextExt)); if (nTmp > 0) return sizeof(TGIFPlainTextExt)+nTmp; break; case BLOCK_IMAGE: TGIFImageDescriptor *pIDescr = reinterpret_cast (&m_pRawData[m_nCurrOffset]); int nLCTSize = (int) (pIDescr>GetPackedValue(ID_PACKED_LOCALCT)*3* (1 GetPackedValue(ID_PACKED_LOCALCTSIZE)+1))); int nTmp = GetSubBlocksLen(m_nCurrOffset+ sizeof(TGIFImageDescriptor) + nLCTSize + 1); if (nTmp > 0) return sizeof(TGIFImageDescriptor) + nLCTSize + 1 + nTmp; break; }; return 0; } UINT WINAPI CPictureEx::_ThreadAnimation(LPVOID pParam) 89 { ASSERT(pParam); CPictureEx *pPic = reinterpret_cast (pParam); pPic->m_bIsPlaying = TRUE; pPic->ThreadAnimation(); pPic->m_bIsPlaying = FALSE; // this thread has finished its work so we close the handle CloseHandle(pPic->m_hThread); // and init the handle to zero (so that Stop() doesn't Wait on it) pPic->m_hThread = 0; return 0; } void CPictureEx::ThreadAnimation() { // first, restore background (for stop/draw support) // disposal method #2 if (m_arrFrames[m_nCurrFrame].m_nDisposal == 2) { HBRUSH hBrush = CreateSolidBrush(m_clrBackground); if (hBrush) { RECT rect = { m_arrFrames[m_nCurrFrame].m_frameOffset.cx, 90 m_arrFrames[m_nCurrFrame].m_frameOffset.cy, m_arrFrames[m_nCurrFrame].m_frameOffset.cx + m_arrFrames[m_nCurrFrame].m_frameSize.cx, m_arrFrames[m_nCurrFrame].m_frameOffset.cy + m_arrFrames[m_nCurrFrame].m_frameSize.cy }; FillRect(m_hMemDC,&rect,hBrush); DeleteObject(hBrush); }; } else // disposal method #3 if (m_hDispMemDC && (m_arrFrames[m_nCurrFrame].m_nDisposal == 3) ) { // put it back BitBlt(m_hMemDC, m_arrFrames[m_nCurrFrame].m_frameOffset.cx, m_arrFrames[m_nCurrFrame].m_frameOffset.cy, m_arrFrames[m_nCurrFrame].m_frameSize.cx, m_arrFrames[m_nCurrFrame].m_frameSize.cy, m_hDispMemDC,0,0, SRCCOPY); // init variables SelectObject(m_hDispMemDC,m_hDispOldBM); 91 DeleteDC(m_hDispMemDC); m_hDispMemDC = NULL; DeleteObject(m_hDispMemBM); m_hDispMemBM = NULL; }; while (!m_bExitThread) { if (m_arrFrames[m_nCurrFrame].m_pPicture) { /////////////////////////////////////////////////////// // Before rendering a frame we should take care of what's // behind that frame. TFrame::m_nDisposal will be our guide: // 0 - no disposal specified (do nothing) // 1 - do not dispose (again, do nothing) // 2 - restore to background color (m_clrBackground) // 3 - restore to previous //////// disposal method #3 if (m_arrFrames[m_nCurrFrame].m_nDisposal == 3) { // prepare a memory DC and store the background in it m_hDispMemDC = CreateCompatibleDC(m_hMemDC); m_hDispMemBM = CreateCompatibleBitmap(m_hMemDC, 92 m_arrFrames[m_nCurrFrame].m_frameSize.cx, m_arrFrames[m_nCurrFrame].m_frameSize.cy); if (m_hDispMemDC && m_hDispMemBM) { m_hDispOldBM = reinterpret_cast (SelectObject(m_hDispMemDC,m_hDispMemBM)); BitBlt(m_hDispMemDC,0,0, m_arrFrames[m_nCurrFrame].m_frameSize.cx, m_arrFrames[m_nCurrFrame].m_frameSize.cy, m_hMemDC, m_arrFrames[m_nCurrFrame].m_frameOffset.cx, m_arrFrames[m_nCurrFrame].m_frameOffset.cy, SRCCOPY); }; }; /////////////////////// long hmWidth; long hmHeight; m_arrFrames[m_nCurrFrame].m_pPicture>get_Width(&hmWidth); m_arrFrames[m_nCurrFrame].m_pPicture>get_Height(&hmHeight); 93 if (m_arrFrames[m_nCurrFrame].m_pPicture->Render(m_hMemDC, m_arrFrames[m_nCurrFrame].m_frameOffset.cx, m_arrFrames[m_nCurrFrame].m_frameOffset.cy, m_arrFrames[m_nCurrFrame].m_frameSize.cx, m_arrFrames[m_nCurrFrame].m_frameSize.cy, 0, hmHeight, hmWidth, -hmHeight, NULL) == S_OK) { Invalidate(FALSE); }; if (m_bExitThread) break; // if the delay time is too short (like in old GIFs), wait for 100ms if (m_arrFrames[m_nCurrFrame].m_nDelay < 5) WaitForSingleObject(m_hExitEvent, 100); else WaitForSingleObject(m_hExitEvent, 10*m_arrFrames[m_nCurrFrame].m_nDelay); if (m_bExitThread) break; // disposal method #2 94 if (m_arrFrames[m_nCurrFrame].m_nDisposal == 2) { HBRUSH hBrush = CreateSolidBrush(m_clrBackground); if (hBrush) { RECT rect = { m_arrFrames[m_nCurrFrame].m_frameOffset.cx, m_arrFrames[m_nCurrFrame].m_frameOffset.cy, m_arrFrames[m_nCurrFrame].m_frameOffset.cx + m_arrFrames[m_nCurrFrame].m_frameSize.cx, m_arrFrames[m_nCurrFrame].m_frameOffset.cy + m_arrFrames[m_nCurrFrame].m_frameSize.cy }; FillRect(m_hMemDC,&rect,hBrush); DeleteObject(hBrush); }; } else if (m_hDispMemDC && (m_arrFrames[m_nCurrFrame].m_nDisposal == 3) ) { // put it back BitBlt(m_hMemDC, m_arrFrames[m_nCurrFrame].m_frameOffset.cx, 95 m_arrFrames[m_nCurrFrame].m_frameOffset.cy, m_arrFrames[m_nCurrFrame].m_frameSize.cx, m_arrFrames[m_nCurrFrame].m_frameSize.cy, m_hDispMemDC,0,0, SRCCOPY); // init variables SelectObject(m_hDispMemDC,m_hDispOldBM); DeleteDC(m_hDispMemDC); m_hDispMemDC = NULL; DeleteObject(m_hDispMemBM); m_hDispMemBM = NULL; }; }; m_nCurrFrame++; if (m_nCurrFrame == m_arrFrames.size()) { m_nCurrFrame = 0; // init the screen for the first frame, HBRUSH hBrush = CreateSolidBrush(m_clrBackground); if (hBrush) { RECT rect = {0,0,m_PictureSize.cx,m_PictureSize.cy}; FillRect(m_hMemDC,&rect,hBrush); 96 DeleteObject(hBrush); }; }; }; } void CPictureEx::Stop() { m_bIsPlaying = FALSE; m_bExitThread = TRUE; SetEvent(m_hExitEvent); if (m_hThread) { // we'll wait for 5 seconds then continue execution WaitForSingleObject(m_hThread,5000); CloseHandle(m_hThread); m_hThread = NULL; } // make it possible to Draw() again ResetEvent(m_hExitEvent); m_bExitThread = FALSE; } HGLOBAL CPictureEx::GetNextGraphicBlock(UINT *pBlockLen, UINT *pDelay, SIZE *pBlockSize, SIZE *pBlockOffset, UINT *pDisposal) { 97 if (!m_pRawData) return NULL; // GIF header + LSDescriptor [+ GCT] [+ Control block] + Data *pDisposal = 0; enum GIFBlockTypes nBlock; nBlock = GetNextBlock(); while ( (nBlock != BLOCK_CONTROLEXT) && (nBlock != BLOCK_IMAGE) && (nBlock != BLOCK_PLAINTEXT) && (nBlock != BLOCK_UNKNOWN) && (nBlock != BLOCK_TRAILER) ) { if (!SkipNextBlock()) return NULL; nBlock = GetNextBlock(); }; if ((nBlock == BLOCK_UNKNOWN) || (nBlock == BLOCK_TRAILER)) return NULL; // it's either a control ext.block, an image or a plain text int nStart = m_nCurrOffset; int nBlockLen = GetNextBlockLen(); 98 if (nBlockLen m_wDelayTime; // store disposal method *pDisposal = pControl>GetPackedValue(GCX_PACKED_DISPOSAL); if (!SkipNextBlock()) return NULL; nBlock = GetNextBlock(); // skip everything until we find data to display // (image block or plain-text block) while ( (nBlock != BLOCK_IMAGE) && (nBlock != BLOCK_PLAINTEXT) && (nBlock != BLOCK_UNKNOWN) && (nBlock != BLOCK_TRAILER) ) { if (!SkipNextBlock()) return NULL; 99 nBlock = GetNextBlock(); nBlockLen += GetNextBlockLen(); }; if ((nBlock == BLOCK_UNKNOWN) || (nBlock == BLOCK_TRAILER)) return NULL; nBlockLen += GetNextBlockLen(); } else *pDelay = -1; // to indicate that there was no delay value if (nBlock == BLOCK_IMAGE) { // store size and offsets TGIFImageDescriptor *pImage = reinterpret_cast (&m_pRawData[m_nCurrOffset]); pBlockSize->cx = pImage->m_wWidth; pBlockSize->cy = pImage->m_wHeight; pBlockOffset->cx = pImage->m_wLeftPos; pBlockOffset->cy = pImage->m_wTopPos; }; if (!SkipNextBlock()) return NULL; HGLOBAL hGlobal = GlobalAlloc(GMEM_FIXED, sizeof(TGIFHeader) + 100 sizeof(TGIFLSDescriptor) + m_nGlobalCTSize + nBlockLen + 1); // for the trailer if (!hGlobal) return NULL; int nOffset = 0; // GMEM_FIXED means we get a pointer unsigned char *pGlobal = reinterpret_cast (hGlobal); CopyMemory(pGlobal,m_pRawData, sizeof(TGIFHeader)+sizeof(TGIFLSDescriptor)+m_nGlob alCTSize); nOffset += sizeof(TGIFHeader)+sizeof(TGIFLSDescriptor)+m_nGlobalCTSize; CopyMemory(pGlobal + nOffset,&m_pRawData[nStart], nBlockLen); nOffset += nBlockLen; pGlobal[nOffset] = 0x3B; // trailer nOffset++; *pBlockLen = nOffset; return hGlobal; 101 } BOOL CPictureEx::IsGIF() const { return m_bIsGIF; } BOOL CPictureEx::IsAnimatedGIF() const { return (m_bIsGIF && (m_arrFrames.size() > 1)); } BOOL CPictureEx::IsPlaying() const { return m_bIsPlaying; } int CPictureEx::GetFrameCount() const { if (!IsAnimatedGIF()) return 0; return m_arrFrames.size(); } COLORREF CPictureEx::GetBkColor() const { return m_clrBackground; 102 } void CPictureEx::OnPaint() { CPaintDC dc(this); // device context for painting LONG nPaintWidth = m_PaintRect.right-m_PaintRect.left; if (nPaintWidth > 0) { LONG nPaintHeight = m_PaintRect.bottom m_PaintRect.top; ::BitBlt(dc.m_hDC, 0, 0, nPaintWidth, nPaintHeight, m_hMemDC, m_PaintRect.left, m_PaintRect.top, SRCCOPY); } else { ::BitBlt(dc.m_hDC, 0, 0, m_PictureSize.cx, m_PictureSize.cy, m_hMemDC, 0, 0, SRCCOPY); }; } BOOL CPictureEx::PrepareDC(int nWidth, int nHeight) { SetWindowPos(NULL,0,0,nWidth,nHeight,SWP_NOMO VE | SWP_NOZORDER); 103 HDC hWinDC = ::GetDC(m_hWnd); if (!hWinDC) return FALSE; m_hMemDC = CreateCompatibleDC(hWinDC); if (!m_hMemDC) { ::ReleaseDC(m_hWnd,hWinDC); return FALSE; }; m_hBitmap = CreateCompatibleBitmap(hWinDC,nWidth,nHeight); if (!m_hBitmap) { ::ReleaseDC(m_hWnd,hWinDC); ::DeleteDC(m_hMemDC); return FALSE; }; m_hOldBitmap = reinterpret_cast (SelectObject(m_hMemDC,m_hBitmap)); // fill the background m_clrBackground = GetSysColor(COLOR_3DFACE); RECT rect = {0,0,nWidth,nHeight}; FillRect(m_hMemDC,&rect,(HBRUSH)(COLOR_WIND OW)); 104 ::ReleaseDC(m_hWnd,hWinDC); m_bIsInitialized = TRUE; return TRUE; } void CPictureEx::OnDestroy() { Stop(); CStatic::OnDestroy(); } void CPictureEx::SetBkColor(COLORREF clr) { if (!m_bIsInitialized) return; m_clrBackground = clr; HBRUSH hBrush = CreateSolidBrush(clr); if (hBrush) { RECT rect = {0,0,m_PictureSize.cx,m_PictureSize.cy}; FillRect(m_hMemDC,&rect,hBrush); DeleteObject(hBrush); }; } #ifdef GIF_TRACING void CPictureEx::WriteDataOnDisk(CString szFileName, HGLOBAL hData, DWORD dwSize) 105 { CFile file; if (!file.Open(szFileName, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyNone)) { TRACE(_T("WriteData: Error creating file %s\n"),szFileName); return; }; char *pData = reinterpret_cast (GlobalLock(hData)); if (!pData) { TRACE(_T("WriteData: Error locking memory\n")); return; }; TRY { file.Write(pData,dwSize); } CATCH(CFileException, e); { TRACE(_T("WriteData: An exception occured while writing to the file %s\n"), 106 szFileName); e->Delete(); GlobalUnlock(hData); file.Close(); return; } END_CATCH GlobalUnlock(hData); file.Close(); } void CPictureEx::EnumGIFBlocks() { enum GIFBlockTypes nBlock; ResetDataPointer(); while(m_nCurrOffset < m_nDataSize) { nBlock = GetNextBlock(); switch(nBlock) { case BLOCK_UNKNOWN: TRACE(_T("- Unknown block\n")); return; break; case BLOCK_TRAILER: 107 TRACE(_T("- Trailer block\n")); break; case BLOCK_APPEXT: TRACE(_T("- Application extension block\n")); break; case BLOCK_COMMEXT: TRACE(_T("- Comment extension block\n")); break; case BLOCK_CONTROLEXT: { TGIFControlExt *pControl = reinterpret_cast (&m_pRawData[m_nCurrOffset]); TRACE(_T("- Graphic control extension block (delay %d, disposal %d)\n"), pControl->m_wDelayTime, pControl->GetPackedValue(GCX_PACKED_DISPOSAL)); }; break; case BLOCK_PLAINTEXT: TRACE(_T("- Plain text extension block\n")); break; 108 case BLOCK_IMAGE: TGIFImageDescriptor *pIDescr = reinterpret_cast (&m_pRawData[m_nCurrOffset]); TRACE(_T("- Image data block (%dx%d %d,%d)\n"), pIDescr->m_wWidth, pIDescr->m_wHeight, pIDescr->m_wLeftPos, pIDescr->m_wTopPos); break; }; SkipNextBlock(); }; TRACE(_T("\n")); } #endif // GIF_TRACING BOOL CPictureEx::SetPaintRect(const RECT *lpRect) { return CopyRect(&m_PaintRect, lpRect); } BOOL CPictureEx::GetPaintRect(RECT *lpRect) { return CopyRect(lpRect, &m_PaintRect); 109 } //====================================== // Sử dụng CPictureEx m_Picture; DDX_Control(pDX, IDC_PICTURE, m_Picture); // IDR_GIF2 : Tên file .gif if (m_Picture.Load(MAKEINTRESOURCE(IDR_GIF2), _T("GIF"))) { m_Picture.Draw(); m_Picture.UnLoad(); } 14.7 Set value for control CEdit CEdit m_txt_Device_Tab_02; DDX_Control(pDX, IDC_EDIT_DEVICE_TAB_02, m_txt_Device_Tab_02); m_txt_Device_Tab_02.SetWindowText(“AAAAA”); 14.8 Lấy Vị trí và giá trị trong combobox CString sType; int nSel = m_cbb_DriverID_Tab_01.GetCurSel(); values choosing - Position if (nSel != LB_ERR) { m_cbb_DriverID_Tab_01.GetLBText(nSel, sType); values for sType - Text } 110 // Get // Set CString str1, str2; int n; for (int i = 0; i < m_pComboBox->GetCount(); i++) { n = m_pComboBox->GetLBTextLen(i); m_pComboBox->GetLBText(i, str1.GetBuffer(n)); str1.ReleaseBuffer(); str2.Format(_T("item %d: %s\r\n"), i, str1.GetBuffer(0)); AFXDUMP(str2); } 14.9 Check đường dẫn tồn tại // 1 : true OK // 0 : fail BOOL DirectoryExists(LPCTSTR szPath) { DWORD dwAttrib = GetFileAttributes(szPath); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } 14.10 Truyền dữ liệu giữa 2 app thông qua tên app Bước 1: Tạo thao tác cần send dữ liệu LRESULT copyDataResult; // PaseriPC : Tên cửa sổ trên UI CWnd *pOtherWnd = CWnd::FindWindow(NULL, _T("PaseriPC")); if (pOtherWnd) { COPYDATASTRUCT cpd; cpd.dwData = 0; // “1” giá trị mình muốn gửi CString txt("1"); cpd.cbData = txt.GetLength(); cpd.lpData = (void*)txt.GetBuffer(txt.GetLength()); copyDataResult = pOtherWnd->SendMessage(WM_COPYDATA, (WPARAM)AfxGetApp()->m_pMainWnd->GetSafeHwnd(), 111 (LPARAM)&cpd); // copyDataResult has value returned by other app } else { AfxMessageBox(_T("Unable to find other app.")); } Bước 2: Tạo sự kiện Trong file .h của UI #include // you will need this BOOL CApp_01Dlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct) { wchar_t wString[1024]; memset(wString, 0, sizeof(wchar_t)* 1024); wcscpy(wString, (LPWSTR)pCopyDataStruct->lpData); // Giá trị được lấy về khi có tác vụ send dữ liệu CString m_rxText = (LPCSTR)(pCopyDataStruct->lpData); //c_RxText.SetWindowText(wString); // gán giá trị lên UI textbox return CDialogEx::OnCopyData(pWnd, pCopyDataStruct); } Bước 3 : Thêm dòng này vào file .cpp trong UI để nó kích hoạt OnCopyData 112 14.11 Close Dialog UINT WorkerThreadProc(LPVOID Param) //Sample function for using in AfxBeginThread { MFC_PropressBar * self = NULL; self = (MFC_PropressBar *)Param; if (self != NULL) { PostMessage(self->m_hWnd, WM_CLOSE, 0, 0); // Dòng này đóng dialog } return 1; } // Gọi hàm AfxBeginThread(WorkerThreadProc, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL); 14.12 Set window Top BOOL MFC_Password::OnInitDialog() { CDialog::OnInitDialog(); // SET WINDOW TOP, BEGIN SetWindowPos(&this->wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); // SET WINDOW TOP, END return TRUE; // return TRUE unless you set the focus to a control } 113 14.13 Chuyển thư mục thực thi lênh command line if (SetCurrentDirectory(“Path”)) { //Chuyển thành công } 14.14 Run cmd không hiển thị màn hình đen #include #include #include #include #include using namespace std; #include #include using namespace std; void RunTest(wchar_t *AppName, wchar_t *CmdLine) { wprintf(L"\nTest Running...\n"); wprintf(L" AppName: %s\n", AppName); wprintf(L" CmdLine: %s\n", CmdLine); PROCESS_INFORMATION processInformation; STARTUPINFO startupInfo; memset(&processInformation, 0, sizeof(processInformation)); memset(&startupInfo, 0, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); BOOL result; 114 wchar_t tempCmdLine[MAX_PATH * 2]; //Needed since CreateProcessW may change the contents of CmdLine if (CmdLine != NULL) { _tcscpy_s(tempCmdLine, MAX_PATH * 2, CmdLine); result = ::CreateProcess(AppName, tempCmdLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation); } else { result = ::CreateProcess(AppName, CmdLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation); } if (result == 0) { wprintf(L"ERROR: CreateProcess failed!"); } else { WaitForSingleObject(processInformation.hProcess, INFINITE); CloseHandle(processInformation.hProcess); CloseHandle(processInformation.hThread); } } #include #include void _tmain(int argc, TCHAR *argv[]) { SetCurrentDirectory(L"C:\\Users\\日本語(にほんご\\AppData\\Local\\TCSI\\PaseriPC"); // Path file .exe // Lệnh cmd cần thực thi. Nhớ them /C RunTest(L"C:\\Users\\日本語(にほんご \\AppData\\Local\\TCSI\\PaseriPC\\UsbUtils.exe", NULL); } 14.15 Lấy ngày giờ khi buld project #include #include #include #include #include #include #include using namespace std; void SplitStr(wstring& strSrc, wchar_t delim, vector& token) 115 { // Delimiters are spaces (\s) and/or commas wstring str(1, delim); str += L"+"; //wregex re(" +"); wregex re(str); wstring& s = strSrc; wsregex_token_iterator it(s.begin(), s.end(), re, -1); wsregex_token_iterator reg_end; for (; it != reg_end; ++it) { token.push_back(it->str()); } return; } //-------------------------------------------------------------------------------// Function: Get_Build_No_Wstr() // Purpose: return wstring value with date time format as // YYYY_MMDD_HHMM format // For example, 2015_0828_1650 // Note: Date Time is got from "COMPILED" time. // #define __STR2WSTR(str) L##str #define _STR2WSTR(str) __STR2WSTR(str) wstring GetBuildNoW() { wchar_t* pWDate = _STR2WSTR(__DATE__); wchar_t* pWTime = _STR2WSTR(__TIME__); /* char *pDate = __DATE__; char *pTime = __TIME__; char *pTimeStamp = __TIMESTAMP__; wprintf(L"pWDate = [%s]\r\n", pWDate); wprintf(L"pWTime = [%s]\r\n", pWTime); printf("pDate [%s]\n", pDate); printf("pTime [%s]\n", pTime); printf("ptimeStamp [%s]\n", pTimeStamp); */ static wchar_t* MonthList[] = { L"", L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun", L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec", }; wstring buildNo; vector vectDate; // pWDate format is like "Aug 28 2015" SplitStr(wstring(pWDate), L' ', vectDate); 116 if (vectDate.size() >= 3) { buildNo += vectDate[2]; //year } buildNo += L"_"; int i = 0; for (i = 0; i < ARRAYSIZE(MonthList); i++) { //Convert "Aug" to "08" if (0 == vectDate[0].compare(MonthList[i])) { wchar_t month[16] = { 0 }; swprintf_s(month, ARRAYSIZE(month), L"%02d", i); buildNo += month; wchar_t date[16] = { 0 }; int iDate = _wtoi(vectDate[1].c_str()); swprintf_s(date, ARRAYSIZE(date), L"%02d", iDate); buildNo += date; break; } } buildNo += L"_"; vector vectTime; // pWTime format is like "16:50:34" SplitStr(wstring(pWTime), L':', vectTime); buildNo += vectTime[0]; //HH buildNo += vectTime[1]; //MM return buildNo; } void main(void) { wstring no = GetBuildNoW(); wprintf(L"No [%s]\r\n", no.c_str()); } 14.16 Show Message AfxMessageBox(_T(“XXXXX”), MB_OK | MB_ICONEXCLAMATION | MB_TOPMOST); 14.17  Xóa Icon trong Cache ie4uinit.exe –ClearIconCache 117 14.18 Mutex #include std::mutex mLock_Exit; mLock_Exit.lock(); // Nội dụng cần mutex mLock_Exit.unlock(); 15. Định nghĩa rồi không cần định nghĩa lại #ifndef _CCONVERT_H_ // Có thể sửa tên #define _CCONVERT_H_ // Có thể sửa tên // Nội dung #endif http://www.smart-arab.com/2014/07/encrypt-decrypt-binary-files-using-des-crypt-in-c/ 15.11 Set tilte in window AfxGetMainWnd()->SetWindowText(L"PaseriPC Current status"); 16. Build MFC release Sửa đường dẫn tương đối : $(SolutionDir)\..\ Bước 1 : Cấu hình property Solution 118 Bước 2: Cấu hình lib 119 Bước 3 : Cấu hình app 120 121 122 123 124 125 126 Cấu hình để chọn chế độ 127 17. SERVER – CLIENT - PIPE SERVER #include #include using namespace std; int main(int argc, const char **argv) { while (1) { wcout [...]... GetDriveType((LPCWSTR)ptr); } } // Call using, Array contain status int A[MAX26]; GetAllDriver(A); 31 14 MFC UI 14.1 Close X 32 // Để trong hàm DoDataExchange CMenu *pMenu; pMenu = GetSystemMenu(FALSE); if (pMenu != NULL) pMenu->EnableMenuItem(SC_CLOSE, MF_BYCOMMAND | MF_DISABLED); // Override nút X // Bước 1 : BEGIN_MESSAGE_MAP(CMFCApplication1Dlg, CDialogEx) ON_WM_CLOSE()//nvnhcmus END_MESSAGE_MAP() // Bước 2 : Xử... BEGIN_MESSAGE_MAP(CMFCApplication1Dlg, CDialogEx) ON_WM_CLOSE()//nvnhcmus END_MESSAGE_MAP() // Bước 2 : Xử lý trong file h afx_msg void OnClose(); // Bước 3 : Xử lý - ẩn màn hình đang hiển thị //nvnhcmus void CMFCApplication1Dlg::OnClose() { #ifdef USING_NONMFC_TRAY // This is set in project settings CSystemTray::MinimiseToTray(GetSafeHwnd()); #else CSystemTray::MinimiseToTray(this); #endif } //~nvnhcmus runas /user:Administrator Example1Server.exe... _pclose(pipe); 2 Malloc char *buffer; //khai báo vùng đệm buffer = (char *)malloc(1024); //cấp phát 1024 bytes if(buffer == NULL) { //xử lý nếu thất bại } else { //xử lý nếu thành công } free(buffer); //sau khi sử dụng xong, giải phóng bộ nhớ //đã cấp phát 3 Memset(), memcpy(), memcmp() http://www.stdio.vn/articles/read/70-cac-ham-memset-memcpy-memcmp-trong-c http://www.stdio.vn/articles/read/107-hien-thuc-va-su-dung-ham-memcmp-memcpy-memset-trong-cc... &bufCharCount)) { for (i = 0; iEnableMenuItem(SC_CLOSE, MF_BYCOMMAND | MF_DISABLED); 13 Get all status letter #include "stdafx.h" #define MAX26 26 void GetAllDriver(int

Ngày đăng: 21/10/2015, 14:17

TỪ KHÓA LIÊN QUAN

w