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
Trang 1Mụ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
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
1 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
Trang 22 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
Trang 314.9 Check đường dẫn tồn tại 111
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-in-C.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);
Trang 44 Ẩ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
Trang 5#endif //ENABLEGROUPBOXCONTROLS_H
- Source Files : tạo class : EnableGroupboxControls.cpp
// EnableGroupboxControls.cpp Version 1.0 - see article at CodeProject.com
// The EnableGroupboxControls function enables or disables all the controls
// contained within a groupbox
// 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
// 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
//
Trang 6// Returns: int - number of controls enabled/disabled If zero is
// returned, it means that no controls lie within the
// rect of the groupbox
::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;
RECT rectChild;
::GetWindowRect(hWndChild, &rectChild);
// check if child rect is entirely contained within groupbox
if ((rectChild.left >= rectGroupbox.left) &&
(rectChild.right <= rectGroupbox.right) &&
(rectChild.top >= rectGroupbox.top) &&
(rectChild.bottom <= rectGroupbox.bottom)) {
//TRACE(_T("found child window 0x%X\n"), hWndChild);
Trang 7// if any controls were affected, invalidate the parent rect
if (rc && IsWindow(hWndParent)) {
::InvalidateRect(hWndParent, NULL, FALSE);
} }
cout << "Creating registry key: " << strKey << endl;
nError = RegCreateKeyEx(hRootKey, strKey, NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL);
}
Trang 106.4 Convert char * to wchar_t
wchar_t *GetWC(const char *c)
Trang 11wchar_t* wstr = L "A wide character string." ;
char* ascii = new char[wcslen(wstr) + 1 ];
wcstombs( ascii, wstr, wcslen(wstr) );
6.14 Convert wchar_t* to int in C
wchar_t * vIn = L "0" ;
int vOut = _wtoi(vIn);
6.15 wstring int
Trang 12std::wstring ws = L "456" ;
int i = std::stoi(ws); // convert to int
std::wstring ws2 = std::to_wstring(i); // and back to wstring
const std:: string time = “abc”;
std:: wstring widestr = std:: wstring (time.begin(), time.end());
std:: wstring_convert <std:: codecvt_utf8 < wchar_t >> converter;
const std:: wstring wide_string = L "呵呵" ;
const std:: string utf8_string = converter.to_bytes(wide_string); std:: wstring_convert <std:: codecvt_utf8_utf16 < wchar_t >> converter_02; std:: wstring wide = converter_02.from_bytes(utf8_string);
return 0;
}
Trang 14char cmdMove[256];
strcpy(cmdMove, "MOVE " );
strcat(cmdMove, ( char *)FILE1);
strcat(cmdMove, " " );
strcat(cmdMove, ( char *) FILE2);
int result = system(cmdMove);
1.5 Open file
system( "start MyDropBox.exe" );
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
#include <psapi.h>
#include <string>
using namespace std;
//PaseriPC Trả về 1 chuỗi result
FILE * pipe = _popen( "tasklist | findstr PaseriPC" , "r" );
_pclose(pipe);
2 Malloc
char *buffer; //khai báo vùng đệm
buffer = (char *)malloc(1024); //cấp phát 1024 bytes
Trang 174 ERROR
Error 1 error C4996: 'fopen': This function or variable may be unsafe Consider using fopen_s instead To disable deprecation, use _CRT_SECURE_NO_WARNINGS See online help for details
Thêm Project Properties -> Configuration Properties -> C/C++ -> Preprocessor ->
Preprocessor Definitions _CRT_SECURE_NO_DEPRECATE
Trang 18{
string str = "HEllo*world*hello." , split;
vector < string > all;
istringstream token(str);
while (getline(token, split, '*' )){
all.push_back(split);
}
for ( int i = 0; i<( int )all.size(); i++){
cout << all[i] << endl;
fsutil file [createnew] <FileName> <Length>
fsutil file [findbysid] <UserName> <Directory>
fsutil file [queryallocranges] offset=<Offset> length=<Length> <FileName> fsutil file [quaeryfileid] <FileName>
fsutil file [queryfilenamebyid] <Volume> <Fileid>
fsutil file [setshortname] <FileName> <ShortName>
fsutil file [setvaliddata] <FileName> <DataLength>
fsutil file [setzerodata] offset=<Offset> length=<Length> <FileName>
7 Create & Start Service
Trang 19printf( "Load Driver\n" );
if (hSCManager)
{
printf( "Create Service\n" );
hService = CreateService (hSCManager, L "filedisk" ,
L "filedisk Driver" , SERVICE_START | DELETE | SERVICE_STOP , SERVICE_KERNEL_DRIVER ,
SERVICE_DEMAND_START , SERVICE_ERROR_IGNORE ,
L "filedisk.sys" , NULL , NULL , NULL , NULL , NULL );
if (!hService) {
hService = OpenService (hSCManager, L "filedisk" ,
SERVICE_START | DELETE | SERVICE_STOP );
}
if (hService) {
printf( "Start Service\n" );
StartService (hService, 0, NULL );
//printf("Press Enter to close service\r\n");
Trang 209 Đường dẫn tương đối trong C/C++
$(SolutionDir)\ \
Trang 2110 File
10.1 Get length
// File get length > 4GB
long long file_length( const char * fpath)
Trang 22// Create file hiden )( #include <Windows.h> )
static int CreateHidenFile(CString filePath, long size)
LARGE_INTEGER volumeSize;
volumeSize.QuadPart = size;
// Preallocate the file
if (!SetFilePointerEx(hFile, volumeSize, NULL, FILE_BEGIN)
Trang 23const std:: string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format
strftime(buf, sizeof (buf), "%Y-%m-%d.%X" , &tstruct);
perror( "Error opening file" );
TRACE ( _T ( "Error opening file" ));
}
else
{
fwrite( "\n" , sizeof ( char ), 1, pFile);
const std:: string time = currentDateTime();
Trang 2410.4 Read full data
// Read all byte in file return char * and filesize
char *ReadFullFile( const char * FilePath , long & fileSize )
struct stat64 st;
stat64 ( FilePath , &st); // Include : #include <sys/stat.h> fileSize = st.st_size;
fseek(pFile, 0, SEEK_SET );
char *buff = new char [ fileSize ];
fread(buff, fileSize , 1, pFile);
Trang 25void ProcessFileByByte( char * data , long sizeFile )
{
char dataByte[ NBYTE ]; // Init nByte
for ( ULONG i = 0; i < ( sizeFile / NBYTE ); i++) // Number Key {
memset(dataByte, 0, NBYTE );
memcpy(dataByte, data + i * NBYTE , NBYTE );
cout << dataByte << "\n" ; }
bool CheckFile( char * pathFile ) {
FILE * pFileRead;
pFileRead = fopen( pathFile , "r" );
if (pFileRead == NULL ) {
return false ; // Not exist }
else {
fclose(pFileRead);
} return true ; // Exist }
Trang 2610.7 Get file Name
10.8 Find string in string
char *StringA = "C:\\PaseriPC\\abc\image.img" ; char *StringB = "C:\\PaseriPC\\" ;
char *pch1 = strstr(( char *) StringA, StringB);
// When NULL : string B have in string A
if ((pch1 == NULL ) {
// do something … }
10.9 Read & Write file Tiếng Nhật
Trang 27// open as a byte stream
std:: wifstream wif( "sample.txt" , std:: ios ::binary);
if (wif.is_open())
{
// apply BOM-sensitive UTF-16 facet
const std:: locale utf8_locale = std:: locale (std:: locale (), :: new std:: codecvt_utf8 < wchar_t >());
wchar_t buffer[ MAXSIZE ];
wchar_t Data[ MAXSIZE ];
Trang 28TRACE ( _T ( "Error opening file" ));
}
else
{
while (!feof(pFile)) {
if (fgetws(buffer, 100, pFile) == NULL ) break ; fputws(buffer, stdout );
for ( int i = 0; i < wcslen(buffer); i++) {
if (buffer[i] == '\n' ) {
buffer[i] = '\0' ; wcscpy(Data, buffer);
break ; }
}
//Xử lý data từng dòng }
wstring t = L "askj dhalk sdjh sadas d" ;
//size_t nPos = t.find(L" ");
Trang 29#include <string>
#include <time.h>
using namespace std;
const std:: string currentDate() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format
strftime(buf, sizeof (buf), "%Y-%m-%d" , &tstruct);
return buf;
}
const std:: string currentDate_Full() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format
strftime(buf, sizeof (buf), "%Y-%m-%d_.%H-%M-%S" , &tstruct); return buf;
11 Get user my computer
const char * user_name_char = getenv( "USER" );
if (!user_name_char)
{
user_name_char = getenv( "USERNAME" );
}
cout << "User name <char> : " << user_name_char << "\n" ;
const wchar_t * user_name = _wgetenv(L "USER" );
if (!user_name)
{
user_name = _wgetenv(L "USERNAME" );
}
Trang 30cout << "User name <wchar_t> : " << user_name << "\n" ;
pMenu->EnableMenuItem( SC_CLOSE , MF_BYCOMMAND | MF_DISABLED );
13 Get all status letter
Trang 31for ( int i = 0; i < 26; i++) {
Trang 3214 MFC UI
14.1 Close X
Trang 33// 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ị
Trang 3414.2 Cắt chuỗi trong CSTRING
Trang 35CStringEx( const CString& stringSrc) : CString( stringSrc ){};
CStringEx( const CStringEx& stringSrc) : CString( stringSrc ){};
CStringEx( TCHAR ch, int nRepeat = 1 ) : CString( ch, nRepeat ){};
CStringEx( LPCTSTR lpch, int nLength ) : CString( lpch, nLength ){};
CStringEx( const unsigned char* psz ) : CString( psz ){};
CStringEx( LPCWSTR lpsz ) : CString( lpsz ){};
CStringEx( LPCSTR lpsz ) : CString( lpsz ){};
CStringEx& Insert(int pos, LPCTSTR s);
CStringEx& Insert(int pos, TCHAR c);
CStringEx& Delete(int pos, int len);
CStringEx& Replace(int pos, int len, LPCTSTR s);
int Find( TCHAR ch, int startpos = 0 ) const;
int Find( LPCTSTR lpszSub, int startpos = 0 ) const;
int FindNoCase( TCHAR ch, int startpos = 0 ) const;
int FindNoCase( LPCTSTR lpszSub, int startpos = 0 ) const;
int FindReplace( LPCTSTR lpszSub, LPCTSTR lpszReplaceWith, BOOL bGlobal = TRUE );
int FindReplaceNoCase( LPCTSTR lpszSub, LPCTSTR lpszReplaceWith,
BOOL bGlobal = TRUE );
int ReverseFind( TCHAR ch ) const{ return CString::ReverseFind(ch);};
int ReverseFind( LPCTSTR lpszSub, int startpos = -1 ) const;
int ReverseFindNoCase( TCHAR ch, int startpos = -1 ) const;
int ReverseFindNoCase( LPCTSTR lpszSub, int startpos = -1 ) const;
CStringEx GetField( LPCTSTR delim, int fieldnum);
CStringEx GetField( TCHAR delim, int fieldnum);
int GetFieldCount( LPCTSTR delim );
int GetFieldCount( TCHAR delim );
CStringEx GetDelimitedField( LPCTSTR delimStart, LPCTSTR delimEnd,
void ExpandMacro(char* pchMacroString);
int GetMacroIndex(char* pchMacroString);
void Concat(const char* pchString);
void GetDateString(char* pchBuffer);
};
#endif
/////////////////////////////////////////////////////////////////////
Trang 36// Insert - Inserts a sub string into the string
// Returns - Reference to the same string object
// pos - Position to insert at Extends the string with spaces if needed
CStringEx& CStringEx::Insert(int pos, LPCTSTR s)
{
int len = lstrlen(s);
if ( len == 0 )
return *this;
int oldlen = GetLength();
int newlen = oldlen + len;
_tcsnset( str+oldlen, _T(' '), pos-oldlen );
_tcsncpy( str+pos, s, len );
}
else
{
// normal insert str = GetBuffer( newlen );
memmove( str+pos+len, str+pos, sizeof(_T(' ')) *(oldlen-pos) ); _tcsncpy( str+pos, s, len );
}
ReleaseBuffer( newlen );
return *this;
}
// Insert - Inserts a character into the string
// Returns - Reference to the same string object
// pos - Position to insert at Extends the string with spaces if needed
Trang 37}
// Delete - Deletes a segment of the string and resizes it
// Returns - Reference to the same string object
// pos - Position of the string segment to remove
// len - Number of characters to remove
CStringEx& CStringEx::Delete(int pos, int len)
{
int strLen = GetLength();
if( pos >= strLen)
return *this;
if(len < 0 ||len > strLen - pos)
len = strLen - pos;
// Replace - Replaces a substring with another
// Returns - Reference to the same string object
// pos - Position of the substring
// len - Length of substring to be replaced
// Find - Finds the position of a character in a string
// Returns - A zero-based index
// startpos - Position to start looking from
int CStringEx::Find( TCHAR ch, int startpos /*= 0*/ ) const
{
// find first single character
LPTSTR lpsz = _tcschr(m_pchData + startpos, (_TUCHAR)ch); // return -1 if not found and index otherwise
return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData);
}
// Find - Finds the position of a substring in a string
Trang 38// Returns - A zero-based index
// lpszSub - Substring to look for
// startpos - Position to start looking from
int CStringEx::Find( LPCTSTR lpszSub, int startpos /*= 0*/ ) const
// FindNoCase - Case insensitive find
// Returns - A zero-based index
// startpos - Position to start looking from
int CStringEx::FindNoCase( TCHAR ch, int startpos /*= 0*/ ) const
{
unsigned int locase = Find( tolower( ch ), startpos );
unsigned int upcase = Find( toupper( ch ), startpos );
return locase < upcase ? locase : upcase;
}
// FindNoCase - Case insensitive find
// Returns - A zero-based index
// lpszSub - Substring to search for
// startpos - Position to start looking from
int CStringEx::FindNoCase( LPCTSTR lpszSub, int startpos /*= 0*/ ) const {
CStringEx sLowerThis = *this;
// FindReplace - Find a substring and replace with another
// lpszReplaceWith - Substring to replace with
// bGlobal - Flag to indicate whether all occurances
int CStringEx::FindReplace( LPCTSTR lpszSub, LPCTSTR lpszReplaceWith,
BOOL bGlobal /*= TRUE*/ ) {
Trang 39int iReplaced = 0;
// find first matching substring
LPTSTR lpsz;
int pos = 0;
int lenSub = lstrlen( lpszSub );
int lenReplaceWith = lstrlen( lpszReplaceWith );
while( (lpsz = _tcsstr(m_pchData + pos, lpszSub)) != NULL ) {
pos = (int)(lpsz - m_pchData);
Replace( pos, lenSub, lpszReplaceWith );
pchLead[0]=0;
Concat(pchAnchor);
pchLead[0]='[';
} pchAnchor=pchLead;
//scan through to the end of macro pchLead=strchr(pchLead,']');
if(pchLead) {
Trang 40} else {
break;
} }
strcat(szTemp,"\\");
} Concat(szTemp);
}
}
void CStringEx::Concat(const char* pchString)
{
CStringData* pOldData = GetData();
ConcatCopy(GetData()->nDataLength, m_pchData, strlen(pchString),pchString); ASSERT(pOldData != NULL);
CString::Release(pOldData);
}