C, C++, MFC, and Windows API FAQs

 C, C++, MFC, and Windows API FAQs 

When I started programming in C++ I ran into many common questions. So I made this page where others can see the questions and answers I have stumbled upon and put a lot of work into it. Hopefully you will be able to find an answer to a programming question you are trying to answer here. Note that most of these are not full tutorials, but rather quick answers.

I have found many of these answers on the Internet, changing some of them to make them a little shorter or easier. I think I gave credit to everyone I took work from, but if not, email me at mpiecyk@@@@gmail.com. Also, please email me if you find an error.

Credit is not required (unless I stated that someone else created the solution, then give credit to them).

This page contains FAQs about the "standard," portable functions of C and C++, and also contains answers that use the MFC (which comes with Visual Studio). Furthermore, many of the answers use the Windows API (which comes with Visual Studio, the Microsoft Platform SDK (which is free), and other places that I haven't tried out. You should be able to figure out if the solutions I provided are too advanced for you or not.

If a solution has red highlighting, it only works with Windows (and you probably have to include <windows.h> or use the MFC.) If a solution has blue highlighting, it should work with most operating systems.

 The FAQs 


How do I execute a program?

Probably the best way to execute a program (in Windows) is to use this code:



If you want to wait for the program to finish, add this above CloseHandle.



To start a program in a temporary DOS window:

system("start E://WINDOWS//system32//mspaint.exe");

How do I open a file so it runs in Paint, Word, etc., (but shows a security message if it is an exe)?

ShellExecute(NULL, NULL, strFile, NULL, NULL, SW_SHOW);

How do I open a folder using My Computer?

ShellExecute(NULL, NULL, <fully_qualified_path_to_folder>, NULL, NULL, SW_SHOWNORMAL);

How do I know if my application is already running?

//is the app already running?
::CreateMutex( NULL, TRUE, TEXT("NAME-088FA2340-B10234-12343-B2346-0070967"));
if(GetLastError() == ERROR_ALREADY_EXISTS)
exit(0);

How do I convert an integer or short to a string?

Using a character array
ASCII
itoa(integer,chararray,10);
//integer to string array, 10 = radix, returns the string array

TCHAR
_itot(integer,chararray,10);
Unicode
_itow(integer,chararray,10);

Using wsprintf
wsprintf(buff,"Value: %d", integer)
params are TCHAR *, so Unicode or ASCII may be used
returns "number of characters stored in the output buffer, not counting the terminating null character."
%f =float
%s=string
%c=char
%d=integer

Using the MFC CString:
CString MFCString;
MFCString.Format("Value: %d", integer);
%f =float
%s=string
%c=char
%d=integer

How do I convert a string to an integer?

Using the Run-time Library
int _ttoi(TCHAR* str)
returns 0 when the input could not be deciphered
returns the int when the input was deciphered correctly

How do I write ANSI or Unicode to console?

int puts( const char *string );
int _putws( const wchar_t *string );
puts also replaces the '/0' with a '/n' for a new line in the console.

Does the length of strlen and wcslen include the terminating null character?

No.

What are the special chars that I can use in my strings?

/n newline == endl
/r carriage return
/t tabulation
/v vertical tabulation
/b backspace
/f page feed
/a alert (beep)
/' single quotes (')
/" double quotes (")
/? question (?)
// inverted slash (/)
/0 null char means end of string
/ - Allows you to continue your string onto the next line. ex. "asdfg/
... hjkl" produces no compile errors.

What happens if I do strcat("ASD",str1)?

The next time you use the string "ASD" it will be screwed up. Use this instead:

char str2[4] = "ASD";
strcat(str2,str1);

How do I use malloc and free?

Example
char * string;
string = (char*)malloc( _MAX_PATH );
if( string == NULL )
printf( "Insufficient memory available/n" );
else
{
printf( "Memory space allocated for path name/n" );
free( string );
printf( "Memory freed/n" );
}

Faster example
void *array;
if ((array = malloc(length)) == NULL)
exit(1);

How do I use calloc?

Function definition
void * calloc (size_t nelements, size_t size);

The two parameters are multiplied to obtain the total size of the memory block to be assigned.

Example
int * bobby;
bobby = (int *) calloc (5, sizeof(int));
if( bobby == NULL )
printf( "Insufficient memory available/n" );
else
{
printf( "Memory space allocated for path name/n" );
free( bobby );
printf( "Memory freed/n" );
}

What's the difference between malloc and new, free and delete?

new is a C++ operator which will allocate memory AND call the constructor of the class for which's object memory is being allocated.

Free is a C function which will free up the memory allocated. but delete is a C++ operator which will free up the allocated memory AND call the destructor of the object.

How do I use realloc to acquire even more memory?

void *realloc( void *memblock, size_t size );
Returns NULL if there is not enough memory.

When I pass an array to a method, does the method alter the actual array or does it make a copy of the array?

The method alters the array. No copy is made. Take a look at this example:

void method(char *buff2)
{
strcpy(buff2,"CHANGHED!!!");
}
int main(int argc, char* argv[])
{
char buff[512];
strcpy(buff,"Hello there!");
printf(buff);
method(buff);
printf(buff); //doesn't say "Hello there!" anymore! Says "CHANGHED!!!"
return 0;
}

How do I remove, for instance, a password from the RAM while my program is running?

SecureZeroMemory(szPassword, sizeof(szPassword));
memset( szPassword, '*', sizeof(szPassword) ); //will replace the password, starting at szPassword, with the '*' character, for a length szPassword

How do I move memory to a different location while my program is running?

Copy Memory

Standard
void *memcpy( void *dest, const void *src, size_t count );
returns the value of dest

Windows API
CopyMemory

MoveMemory

How do I create a data segment where I can store public variables that can be accessed by any application?

#pragma data_seg(".SHARED")
char sharedvar[256] = {0}; // variables MUST be initialized,
#pragma data_seg()
#pragma comment(linker, "/section:.SHARED,RWS") //if you don't put this in the DLL, the data can't even be shared from function to function!

How can I make a region of data that can be accessed by other applications?

GlobalAlloc() (slower than heap) (the clipboard and DDE uses this)
heap functions
more...

Is my application data safe in the RAM?

Yes (mostly). All threads of a process can access its virtual address space. However, threads cannot access memory that belongs to another process, which protects a process from being corrupted by another process (unless the program crashes).

Explain the "virtual addresses" that are used by all of my programs.

Memory management is no longer a problem because the system is free to manage memory by moving pages of physical memory without affecting the virtual addresses.
If the threads of a process attempt to use more physical memory than is currently available, the system pages some the memory contents to disk.
The total amount of virtual address space available to a process is limited by physical memory and the free space on disk available for the paging file.
Physical storage and the virtual address space of each process are organized into pages, units of memory, whose size depends on the host computer. For example, on x86 computers the host page size is 4 kilobytes.
When a page is moved in physical memory, the system updates the page maps of the affected processes.
When the system needs space in physical memory, it moves the least recently used pages of physical memory to the paging file.

How many bytes is a pointer (in Windows XP)?

On Windows XP (32-bit edition)
4 bytes
On Windows XP 64-bit edition
8 bytes

Therefore, the 4 byte pointer can point to anywhere in a total of 4 GB of memory
and the 8 byte pointer can point to 17,179,869,184 (17 trillion) GB of memory

How can I make a char array the exact size to hold two strings?

char gray[] = "Gray";
char cat[] = "Cat";
char * graycat = malloc(strlen(gray) + strlen(cat) + 1);
strcpy(graycat, gray);
strcat(graycat, cat);

How do I know if a file exists?

/**
* Returns true if the file or directory exists and false if neither exists.
*
* @param filepath file path, can be relative or absolute
* @return true if the file or directory exists
*/
bool FileExists(const TCHAR* filepath) {
struct _stat buf;
return _tstat(filepath, &buf)==0;
}

How do I know if a file can be read?

MFC
CFile f;
int success=f.Open(fileLocation,CFile::modeRead);
if(success)
{ ...

If you're not using the MFC, you can use this instead:

ASCII:

#include <stdio.h>
FILE *file;
file = fopen( fileLocation, "r" );
if( file == NULL )
break;
fclose(file);
(or _wfopen for wide characters)

Unicode:

#include <stdio.h>
FILE *file;
file = _wfopen( fileLocation, "r" );
if( file == NULL )
break;
fclose(file);

How can I get information about a file or directory?

DWORD dwAttr = GetFileAttributes("C://Windows");
if(dwAttr == 0xffffffff)
{
DWORD dwError = GetLastError();
if(dwError == ERROR_FILE_NOT_FOUND)
{
// file not found
}
else if(dwError == ERROR_PATH_NOT_FOUND)
{
// path not found
}
else if(dwError == ERROR_ACCESS_DENIED)
{
// file or directory exists, but access is denied
}
else
{
// some other error has occured
}
}
else
{
if(dwAttr & FILE_ATTRIBUTE_DIRECTORY)
{
// this is a directory
if(dwAttr & FILE_ATTRIBUTE_ARCHIVE)
// Directory is archive file
if(dwAttr & FILE_ATTRIBUTE_COMPRESSED)
// Directory is compressed
if(dwAttr & FILE_ATTRIBUTE_ENCRYPTED)
// Directory is encrypted
if(dwAttr & FILE_ATTRIBUTE_HIDDEN)
// Directory is hidden
if(dwAttr & FILE_ATTRIBUTE_READONLY)
// Directory is read-only
if(dwAttr & FILE_ATTRIBUTE_REPARSE_POINT)
// Directory has an associated reparse point
if(dwAttr & FILE_ATTRIBUTE_SYSTEM)
// Directory is part or used exclusively by the operating system
}
else
{
// this is an ordinary file
if(dwAttr & FILE_ATTRIBUTE_ARCHIVE)
// File is archive file
if(dwAttr & FILE_ATTRIBUTE_COMPRESSED)
// File is compressed
if(dwAttr & FILE_ATTRIBUTE_ENCRYPTED)
// File is encrypted
if(dwAttr & FILE_ATTRIBUTE_HIDDEN)
// File is hidden
if(dwAttr & FILE_ATTRIBUTE_NOT_CONTENT_INDEXED)
// File will not be indexed
if(dwAttr & FILE_ATTRIBUTE_OFFLINE)
// Data of file is not immediately available
if(dwAttr & FILE_ATTRIBUTE_READONLY)
// File is read-only
if(dwAttr & FILE_ATTRIBUTE_REPARSE_POINT)
// File has an associated reparse point
if(dwAttr & FILE_ATTRIBUTE_SPARSE_FILE)
// File is a sparse file
if(dwAttr & FILE_ATTRIBUTE_SYSTEM)
// File is part or used exclusively by the operating system
if(dwAttr & FILE_ATTRIBUTE_TEMPORARY)
// File is being used for temporary storage
}
}

How do I delete a file that is not read-only?

Windows API function
BOOL DeleteFile("myfile.txt")

Standard Library
#include <stdio.h>
if( remove( "myfile.txt" ) == -1 )
"Error deleting file"
else
"File successfully deleted"

How do I change a file from read-only to writable?

#include <sys/stat.h>

if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
_wchmod(FileName, _S_IWRITE); // change read-only file mode

_S_IWRITE = Writing permitted
_S_IREAD | _S_IWRITE = Reading and writing permitted

How do I extract a resource while my program is running?

//by adrian cooper (and edited by me)
//e.g. ExtractBinResource(TEXT("BIN"), IDR_BIN1, TEXT("E://file.exe") );
void ExtractBinResource( LPCTSTR ResName, int nResourceId, LPCTSTR strOutputName )
{
HGLOBAL hResourceLoaded; // handle to loaded resource
HRSRC hRes; // handle/ptr. to res. info.
char *lpResLock; // pointer to resource data
DWORD dwSizeRes;
// find location of the resource and get handle to it
hRes = FindResource( NULL, MAKEINTRESOURCE(nResourceId), ResName);
// loads the specified resource into global memory.
hResourceLoaded = LoadResource( NULL, hRes );
// get a pointer to the loaded resource!
lpResLock = (char*)LockResource( hResourceLoaded );
// determine the size of the resource, so we know how much to write out to file!
dwSizeRes = SizeofResource( NULL, hRes );
/*
LPCTSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode, 0 = do not allow other processes to read / write until we're finished
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
*/
HANDLE file = CreateFile(strOutputName,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if(file!=INVALID_HANDLE_VALUE)
{
printf("File opened.");
/*
HANDLE hFile,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
*/
DWORD bytesWritten;
WriteFile(file,(LPCVOID)lpResLock,dwSizeRes,&bytesWritten,NULL);
CloseHandle(file);
}
}

How do I write to a file using the Platform SDK?

HANDLE file = CreateFile(strOutputName,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if(file!=INVALID_HANDLE_VALUE)
{
printf("File opened.");
/*
HANDLE hFile,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
*/
DWORD bytesWritten;
WriteFile(file,(LPCVOID)lpResLock,dwSizeRes,&bytesWritten,NULL);
CloseHandle(file);
}

How do I read from a file using the Platform SDK?

HANDLE file = CreateFile(InfoClient,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(file!=INVALID_HANDLE_VALUE)
{
CloseHandle(file);
}

How do I get a file's size using the Platform SDK?

DWORD GetFileSize(
HANDLE hFile,
LPDWORD lpFileSizeHigh (this can equal NULL)
) != INVALID_FILE_SIZE

How do I copy a file?

BOOL CopyFile(
LPCTSTR lpExistingFileName,
LPCTSTR lpNewFileName,
BOOL bFailIfExists
);

How do I get the Windows directory and drive letter?

UINT GetWindowsDirectory(
LPTSTR lpBuffer,
UINT uSize
);

How do I get the "Application Data" directory?

Make a string variable called AppDir

Get the User App Data Directory

#include <shlobj.h>
ITEMIDLIST* pidl;
HRESULT hRes = SHGetSpecialFolderLocation( NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE , &pidl );
if (hRes==NOERROR)
{
SHGetPathFromIDList( pidl, AppDir );
}

Get the Common App Data Directory

#include < shlobj.h>
ITEMIDLIST* pidl;
HRESULT hRes = SHGetSpecialFolderLocation( NULL, CSIDL_COMMON_APPDATA|CSIDL_FLAG_CREATE , & pidl );
if (hRes==NOERROR)
{
SHGetPathFromIDList( pidl, AppDir );
}

How do I get the maximum length that a Windows path can be?

Use the constant MAX_PATH (which is 260 btw -- 257 for the letters and special characters like /, 2 for the C:, and 1 for the '/0')

How do I know if a directory or folder exists?

//if the directory exists
DWORD dwAttr = GetFileAttributes(str);
if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY))

How do I create a directory or folder?

Windows API
CreateDirectory( "E://My Folder//ads//", NULL);

Windows 2000 and greater
#define _WIN32_WINNT 0x0500 //define windows version to "Windows 2000"
#define WINVER 0x0500 //define windows version to "Windows 2000"
#include <shlobj.h>
import shell32.lib
SHCreateDirectory(HWND hwnd, LPCWSTR pszPath )==ERROR_SUCCESS
//this version will create the directory and all of the sub-directories

Standard Library
#include < direct.h>
int mkdir(char *pathname);
0=success
-1=failure

How do I get the working directory or folder that my program is running in?

Using the standard libraries
#include < direct.h>
_getcwd(buff,sizeof(buff));

Using the MFC
//sets the working directory, such as C:, E:/my folder, etc.
void SetWorkingDirectory()
{
TCHAR str[MAX_PATH];
GetModuleFileName(NULL, str, MAX_PATH);
CString strDir(str);
workingDir = strDir.Left(strDir.ReverseFind(_T('//')));
}

How do I delete a directory and all of the files inside of it, including the read-only files?

There is no Shell function that deletes a directory and all of its files, so we can use Feroz's function:

Uses the Windows API:

//By Feroz Zahid
BOOL DeleteDirectory(const TCHAR* sPath) {
HANDLE hFind; // file handle
WIN32_FIND_DATA FindFileData;

TCHAR DirPath[MAX_PATH];
TCHAR FileName[MAX_PATH];

_tcscpy(DirPath,sPath);
_tcscat(DirPath,"//*"); // searching all files
_tcscpy(FileName,sPath);
_tcscat(FileName,"//");

hFind = FindFirstFile(DirPath,&FindFileData); // find the first file
if(hFind == INVALID_HANDLE_VALUE) return FALSE;
_tcscpy(DirPath,FileName);

bool bSearch = true;
while(bSearch) { // until we finds an entry
if(FindNextFile(hFind,&FindFileData)) {
if(IsDots(FindFileData.cFileName)) continue;
_tcscat(FileName,FindFileData.cFileName);
if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {

// we have found a directory, recurse
if(!DeleteDirectory(FileName)) {
FindClose(hFind);
return FALSE; // directory couldn't be deleted
}
RemoveDirectory(FileName); // remove the empty directory
_tcscpy(FileName,DirPath);
}
else {
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
_chmod(FileName, _S_IWRITE); // change read-only file mode
if(!DeleteFile(FileName)) { // delete the file
FindClose(hFind);
return FALSE;
}
_tcscpy(FileName,DirPath);
}
}
else {
if(GetLastError() == ERROR_NO_MORE_FILES) // no more files there
bSearch = false;
else {
// some error occured, close the handle and return FALSE
FindClose(hFind);
return FALSE;
}

}
}
FindClose(hFind); // closing file handle

return RemoveDirectory(sPath); // remove the empty directory

}

BOOL IsDots(const TCHAR* str) {
if(_tcscmp(str,".") && _tcscmp(str,"..")) return FALSE;
return TRUE;
}

How do I enable Unicode in my MFC program?

MFC
If the symbol _UNICODE is defined for a build of your program, TCHAR is defined as type wchar_t, a 16-bit character encoding type; otherwise, it is defined as char, the normal 8-bit character encoding. Under Unicode, then, CStrings are composed of 16-bit characters. Without Unicode, they are composed of characters of type char.

Windows API
If the symbol UNICODE is defined before including < windows.h>, the windows functions will be set for Unicode. The standard libraries use TCHAR, so define both _UNICODE and UNICODE.

Placing L before a string converts it to Unicode, but this does not work correctly for Windows functions for some reason.

Use the _T( ) macro to acquire Unicode strings for a MFC application, and use the TEXT( ) macro to acquire Unicode strings for a Windows application.

Make these substitutions for char
TCHAR Where you would use char.
LPTSTR Where you would use char* or TCHAR*
LPCTSTR Where you would use const char*. CString provides the operator LPCTSTR to convert between CString and LPCTSTR, which is highly convenient.

I've defined _UNICODE but now my MFC app says: unresolved external symbol "_WinMain@16". Help!

In the Output category of the Link tab in the Project Settings dialog box, set the Entry Point Symbol to wWinMainCRTStartup.

How do I convert char* to wchar_t* (or ASCII to Unicode)?

Here's a function I wrote, but it can be improved if you don't like it:
//after calling this function make sure to free() the result when done
wchar_t* ASCIIToUnicode(const char *ascii, const int length )
{
//first it would be best to discover where the '/0' is located
int i;
for(i=0;i<length;++i)
{
if(ascii[i]=='/0')
break;
}
++i;
//now we can make the actual Unicode array
char *unicode = (char*)calloc(i,sizeof(wchar_t));
if(unicode==NULL)
exit(1);
for(int j=0;j<i;++j)
{
unicode[j*2]=ascii[j];
unicode[j*2+1]='/0';
}
return (wchar_t*)unicode;
}

Or try this function (I couldn't get it to work however)
mbstowcs( server, argv[1], MAXLEN ); (server = w_char with length MAXLEN, argv[1] = constant char)

What are some Unicode string functions that I can use (and how do they compare with their ASCII counterparts)?

ASCII
strcpy
strlen
strcat
strcmp

TCHAR ( #include <tchar.h> )
_tcscpy
_tcslen
_tcscat
_tcscmp

Using Windows LPTSTR
lstrcpy
lstrlen
lstrcat
lstrcmp

Unicode
wcscpy
wcslen
wcscat
wcscmp

How do I get a MFC window's handle?

Simply use the variable m_hWnd.

How do I get the handle (HWND) of my console program?

HWND GetConsoleWindow();

How do I get the HWND of the desktop?

GetDesktopWindow();

How do I read or write to the registry?

HKEY hKey; //remember to call RegCloseKey when finished
DWORD exists; //will become either REG_CREATED_NEW_KEY or REG_OPENED_EXISTING_KEY
/*
HKEY hKey,
LPCTSTR lpSubKey,
DWORD Reserved,
LPTSTR lpClass,
DWORD dwOptions,
REGSAM samDesired, = needs to have KEY_QUERY_VALUE so we can query the value (KEY_ALL_ACCESS includes that)
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
PHKEY phkResult,
LPDWORD lpdwDisposition
*/
if(::RegCreateKeyEx(HKEY_CURRENT_USER,TEXT("Software//My Folder//myvalues"),NULL,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,&exists)==ERROR_SUCCESS)
{
//a new key was created
if(exists==REG_CREATED_NEW_KEY)
{
printf("New key/n");
//write a value to the registry
/*
HKEY hKey,
LPCTSTR lpValueName,
DWORD Reserved,
DWORD dwType,
const BYTE* lpData,
DWORD cbData
*/
DWORD type = REG_DWORD;
DWORD longValue = 40;
DWORD size = sizeof(DWORD);
if(::RegSetValueEx(hKey,TEXT("Version"),NULL,type,(BYTE*)(&longValue),size)==ERROR_SUCCESS)
{
printf("Wrote a value of 40 to the key./n");
}
else
{
printf("Failed to write a value of 40 to the key./n");
}
}
//the original key was opened
else
{
printf("Opened old key/n");
//get a value from the key
/*
HKEY hKey,
LPCTSTR lpValueName,
LPDWORD lpReserved,
LPDWORD lpType, = REG_BINARY (anything), REG_DWORD (long), REG_SZ (string)
LPBYTE lpData,
LPDWORD pcbData = First you input the size of the pvData buffer. After the function completes, it stores the amount of bytes that were copied to pvData (useful for strings), otherwise we get an error
*/
DWORD type = REG_DWORD;
DWORD longValue;
DWORD size = sizeof(DWORD);
if(::RegQueryValueEx(hKey,TEXT("Version"),NULL,&type,(LPBYTE)&longValue,&size)==ERROR_SUCCESS)
{
printf("Acquired the value.");
}
else
{
printf("Failed to acquire the value.");
}
}
RegCloseKey(hKey);
}
else
{
printf("Could not open key./n");
}

How do I delete a value in the registry?

if(RegDeleteValue(hKey,TEXT("Version"))==ERROR_SUCCESS)
printf("Deleted the value.");
else
printf("Failed to delete the value.");

How do I delete a key (and all of its subkeys) in the registry?

//import shlwapi.lib

#include < shlwapi.h>

if(SHDeleteKey(HKEY_CURRENT_USER,TEXT("Software//My Folder"))==ERROR_SUCCESS)
printf("Deleted the key.");
else
printf("Failed to delete the key.");

How do I close a modal dialog without using the standard OK button, Cancel button, or exit buttons?

EndModalLoop(int nResult);

How do I stop my dialog box from closing when the user presses Enter (Return) or Escape?

Place this function in the dialog's class and add it to the header as well.
// stops the default behavior of the Return and Escape keys
// http://www.codersource.net/
BOOL CCreateDirDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if(pMsg->message==WM_KEYDOWN)
{
if(pMsg->wParam==VK_RETURN || pMsg->wParam==VK_ESCAPE)
pMsg->wParam=NULL ;
}
return CDialog::PreTranslateMessage(pMsg);
}

How do I create a modeless dialog?

NewDialog *dlg;
dlg = new NewDialog;
dlg->Create(IDR_MYDIALOG);
dlg->ShowWindow(1);

How do I get a window to be shown or hidden?

ShowWindow(command);
command=SW_SHOW,SW_HIDE,SW_MAXIMIZE,SW_MINIMIZE,SW_SHOWDEFAULT (Puts the window in the spot where it started up)

How do I set a hotkey for my application?

When the program starts...
if( RegisterHotKey(m_hWnd, 200, MOD_ALT | MOD_SHIFT | MOD_WIN, 'R')==FALSE ) //200 should be a unique id
AfxMessageBox("Failed to set the hotkey.");
To handle the hotkey in BEGIN_MESSAGE_MAP(CHotKeyTestDlg, CDialog)...
ON_MESSAGE(WM_HOTKEY,OnHotKey)
Subsequently you define the function...
LRESULT OnHotKey(WPARAM wParam, LPARAM lParam);
You need to check wParam in the function to see if it contains the id of your hotkey
if( wParam == 200)
When the window is closed ( OnStop() and OnDestroy() to be extra sure )...
UnregisterHotKey(m_hWnd,200);

How do I get whether a key or mouse button is pushed without using hooks?

GetAsyncKeyState();

How do I set the position of the mouse cursor?

BOOL SetCursorPos(x,y); //returns whether the operation was a success

How do I get the position of the mouse cursor?

Definition
BOOL GetCursorPos(LPPOINT lpPoint
);

MFC Example
POINT point;
GetCursorPos(&point);
AfxMessageBox(_itow(point.x,textArray,10));

How do I simulate a mouse press or keyboard press?

//mouse input
INPUT input;
input.type=INPUT_MOUSE;
MOUSEINPUT mouseInput;
mouseInput.dx=0;
mouseInput.dy=0;
mouseInput.mouseData=NULL;
mouseInput.dwFlags=MOUSEEVENTF_LEFTDOWN;
mouseInput.time=0;
mouseInput.dwExtraInfo=0;
input.mi=mouseInput;
if(!::SendInput(1,&input,sizeof(INPUT)))
{
AfxMessageBox(_T("Error sending input."));
}
//(Unicode) keyboard input
INPUT inputKey;
inputKey.type=INPUT_KEYBOARD;
KEYBDINPUT keyInput;
keyInput.wVk=0;
keyInput.wScan=_T('a');
keyInput.dwFlags=KEYEVENTF_UNICODE;
keyInput.time=0;
keyInput.dwExtraInfo=0;
inputKey.ki=keyInput;
if(!::SendInput(1,&inputKey,sizeof(INPUT)))
{
AfxMessageBox(_T("Error sending input."));
}

How do I let a program run in invisible mode where no windows or console boxes come up?

#pragma comment(linker, "/subsystem:/"windows/" /entry:/"mainCRTStartup/"")

How do the arguments of a console program work?

You start off with:
int main( int argc, char *argv[] )
argv[0] should be the complete path of the executable
argc is the number of arguments provided (arguments with spaces in between), and should always be greater than one, since argv[0] is the path.

If you want to make a Windows console that features Unicode arguments, use:
void wmain( int argc, TCHAR *lpszArgv[ ])

or you could use yet another startup:
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])

How do I get the CWinApp that made my dialog while in the dialog class?

CWinApp* AFXAPI AfxGetApp( );

How do I make a thread function?

//Thread
AfxBeginThread(ServerThread,this); //if you want the thread to have access to the current object then pass "this" into the thread's parameter
static UINT ServerThread(LPVOID pParam);

Why do many header files have "#ifdef __cplusplus" and "extern "C" { "?

#ifdef __cplusplus
extern "C" {
#endif
//all of the code of a long header file goes here
#ifdef __cplusplus
}
#endif

if __cplusplus is defined, we are compiling C++ code
extern "C" makes the compiler simply compile C code
for example, if we used a namespace for the C code, the C code wouldn't get a namespace
since we told the compiler we only want fast C code.

How do I link to a library without picking it as an option in Visual Studio?

#pragma comment (lib, "libname")

How do I log in with LogonUser?

HANDLE hToken;
if(LogonUser(TEXT("User"),TEXT("."),TEXT("password"),LOGON32_LOGON_NETWORK,LOGON32_PROVIDER_DEFAULT,&hToken))
printf("Logged in");
else
printf("Login failed");

If I define a variable in one .cpp file, will the definition work for all of the files?

No, the definition will only work for the file you defined.

Why put :: before function names?

You may put :: before a C functions name, like the Windows Software Development Kit's function ::PostMessage(). The Windows SDK ::PostMessage has four paramters. On the other hand, the CWnd class has a PostMessage function too, but this one only has three parameters. If you are writing a CWnd class function in which you wish to call a function which happens to have the same name, you place :: before it.

How do I define my application for Windows 2000 or Windows XP so I can include identifiers like MOUSEINPUT?

#define _WIN32_WINNT 0x0501 //define windows version to "Windows XP"
#define WINVER 0x0501 //define windows version to "Windows XP"

#define _WIN32_WINNT 0x0500 //define windows version to "Windows 2000"
#define WINVER 0x0500 //define windows version to "Windows 2000"

#define _WIN32_WINDOWS 0x0410 //define windows version to "Windows 98"
#define WINVER 0x0410 //define windows version to "Windows 98"

How do I make a lot of radio buttons in different groups?

Put some radio buttons in one group box, and the other radio buttons in another group box
Check "group" for the first radio button in each group box
Now you can select a bunch of different radio boxes at once as long as they're in a group box

If I define a variable inside of the stdafx.h file, will the definition work for all of the files?

Yes, even if you put the definition inside of the #if !defined(AFX_STDAFX_H__D...) condition (which makes sense since the variable AFX_STDAFX_H__D... will not be defined for every file and will need to be defined several times.)

Anyway the stdafx.h file should be included in every .cpp file so that is why it should work

How do I determine the Operating System (OS)?

//by Agus Kurniawan
// Expand the OS and NTVERSION environment variables.
OSVERSIONINFO osv;
osv.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

if(GetVersionEx(&osv))
{
CString ServiceRelease = osv.szCSDVersion; //note: szCSDVersion = service pack release
switch(osv.dwPlatformId)
{
case VER_PLATFORM_WIN32s: //Win32s on Windows 3.1.
a_OS = "Microsoft ® Windows 3.1(TM)";
break;
case VER_PLATFORM_WIN32_WINDOWS: //WIN32 on 95 or 98
//determine if Win95 or Win98
if(osv.dwMinorVersion == 0)
{
a_OS = "Microsoft ® Windows 95(TM) " + ServiceRelease;
}
else if(osv.dwMinorVersion == 10) {
a_OS = "Microsoft ® Windows 98(TM) " + ServiceRelease;
}
if(osv.dwMinorVersion == 90)
{
a_OS = "Microsoft ® Windows Millenium(TM) " + ServiceRelease;
}
break;
case VER_PLATFORM_WIN32_NT: //Win32 on Windows NT.
if(osv.dwMajorVersion == 4)
{
a_OS = "Microsoft ® Windows NT(TM) " + ServiceRelease;
}
else if(osv.dwMajorVersion == 5)
{
a_OS = "Microsoft ® Windows 2000(TM)" + ServiceRelease;
}
break;
default:
a_OS = _T("");
}//end switch
}//end if

Does "break" break out of every for and while loop?

No, "break" only breaks out of one level of a for or while loop.

How does ^ work?

^ means "exclusive or."

If a==b==true, then a^b==false, otherwise this is the same as | (or).

In English, if both variable A and variable B are true, then TRUE ^ (or) TRUE is false.

What does =0 do?

virtual int area (void) =0;
It makes the class an abstract base, which means you can't instantiate the class.

How do I use goto?

loop:
i++;
goto loop;

What does inline do?

inline int sum(int a, int b) {return a+b;} - replaces every call to this function with this code

This is faster, but takes up more space.

How does typedef work?

typedef can be used to make programs easily changeable and shorter.

Form

typedef existing_type new_type_name;

e.g. typedef char c;

What does friend do?

friend allows a member to be accessed anywhere or allows a class to access anything in the current class being defined.

What does virtual do?

virtual means that a pointer should go to the more precisely defined function in a sub-class, if it exists.

You should use it if you know that you will have derived classes and you want those derived classes to have the most precise function.

What are templates?

template - template <class identifier> function_declaration; - Templates allow to create generic functions that admit any data type as parameters and return a value without having to overload the function with all the possible data types. Templates are not compiled until an instantiation of a whatever class is required

How do I write a switch statement?

switch (x) {
case 1:
cout << "x == 1";
break;
case 2:
cout << "x == 2";
break;
default:
cout << "x can't be 1 or 2!";
}

How do min and max work?

The function definitions of min and max are simple:

min(a,b) and max(a,b)

They return which value is smaller or bigger.

What can I do to the DOS console to make it look fancier?

Lots of things!

#include < conio.h>
textbackground(BLUE) sets the background color for text
clrscr() clears the entire screen with the background color
cprintf(string) prints from the cursor
textcolor(MAGENTA) changes the text color
gotoxy(x,y) goes to the position x,y (1,1)=up-left
getch() pauses
delline() deletes the current line and moves everything else above it where there's room
gettext(int left, int top, int right, int bottom, void *destin) copies whatever is on the screen into destin
puttext(int left, int top, int right, int bottom, void *source) puts the text in the rectangle on the screen
_setcursortype(int cur_t) _NOCURSOR, _NORMALCURSOR, _SOLIDCURSOR
textmode(C4350); sets the size and colors of the DOS window

Is "int a(5);" acceptable?

Yes.

How do I compile on Linux with g++?

To compile:

g++ main.cpp -o main

To run:

./main

How do I make a simple question dialog?

Using the MFC
if( AfxMessageBox(_T("Pick yes or no."), MB_YESNO|MB_ICONQUESTION|MB_TOPMOST ) == IDYES )
Using the Windows API
if( ::MessageBox(NULL, TEXT("Pick yes or no."), TEXT("Pick yes or no."), MB_YESNO|MB_ICONQUESTION|MB_TOPMOST ) == IDYES )

How do I display a character?

ASCII
MFC
char str[2];
str[0]=CHAR here;
str[1]='/0';
AfxMessageBox(str);
Windows API
char str[2];
str[0]=CHAR here;
str[1]='/0';
::MessageBox(NULL, str, "Character display", MB_OK|MB_TOPMOST);
Unicode
MFC
wchar_t str[2];
str[0]=WCHAR here;
str[1]='/0';
AfxMessageBox(str);
Windows API
wchar_t str[2];
str[0]=WCHAR here;
str[1]='/0';
::MessageBox(NULL, str, TEXT("Character display"), MB_OK|MB_TOPMOST);

How do I display an integer?

::MessageBox(NULL, _itot(INTVALUE,strTemp,10), TEXT("Int value"), MB_OK|MB_TOPMOST);

How do I create an dialog which allows me to choose a file to open?

CFileDialog f(TRUE);
f.m_ofn.lpstrTitle = _T("Choose a file to upload into the current directory...");
if(f.DoModal()==IDOK)
{
SetButtons(false);
f.GetPathName(); -> returns a CString of the full path of the file
}

How do I give my console application an icon?

Make an icon that has this ID in Visual Studio: 'IDR_MAINFRAME'.

How do I create the Windows XP style / look and feel for my MFC app?

by Alexander Simanov

Save this in the "res" folder:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
manifestVersion="1.0">
<assemblyIdentity
version="1.0.0.0"
processorArchitecture="X86"
name="Microsoft.Windows.YourApplication"
type="win32"
/>
<description>YourApplication</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>

Add two lines to the resource.h file

#define IDR_MANIFEST 1
#define RT_MANIFEST 24

Open up "res/???.rc2" and add

IDR_MANIFEST RT_MANIFEST MOVEABLE PURE
"res//ApplicationManifestXMLFile"

Modify the InitInstance method

InitCommonControls(); // initialize common control library
CWinApp::InitInstance(); // call parent class method

And you're done!

How do I access a MFC control without making it a variable?

CEdit *ebptr = (CEdit *) GetDlgItem(IDC_EDIT1);

How do I enable/disable a "Window"?

m_button.EnableWindow(); //enables
m_button.EnableWindow(FALSE); //disables

How do I know if a check box (CButton) is checked?

if(m_check.GetCheck() == BST_CHECKED)

How do I get a list of all the connected computers on a Windows network?

#include <stdio.h>
#include <windows.h>
#include < winnetwk.h>
#pragma comment (lib, "mpr")

//by rxbagain
void EnumLocalNetwork(NETRESOURCE *lpnr)
{
HANDLE hEnum;
DWORD cEntries = -1, cbBuffer = 0x4000;
if (::WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, lpnr, &hEnum) == 0) {
if ((lpnr = (LPNETRESOURCE)::GlobalAlloc(GPTR, cbBuffer)) != NULL) {
while (::WNetEnumResource(hEnum, &cEntries, lpnr, &cbBuffer) == 0) {
for (int ctr = 0; ctr < (int)cEntries; ctr++) {
if (lpnr[ctr].dwDisplayType == RESOURCEDISPLAYTYPE_NETWORK ||
lpnr[ctr].dwDisplayType == RESOURCEDISPLAYTYPE_DOMAIN)
EnumLocalNetwork(&lpnr[ctr]);
else {
printf(lpnr[ctr].lpRemoteName);
printf("/n");
}
}
cEntries = -1;
cbBuffer = 0x4000;
}
::GlobalFree(lpnr);
}
::WNetCloseEnum(hEnum);
}
}
int main()
{
printf("Start/n");
EnumLocalNetwork(NULL);
printf("Finish/n");
return 0;
}

How do I get a list of all the shares on a Windows network?

#include <stdio.h>
#include <windows.h>
#include < winnetwk.h>
#pragma comment (lib, "mpr")

//by rxbagain
void EnumLocalNetwork(NETRESOURCE *lpnr)
{
HANDLE hEnum;
DWORD cEntries = -1, cbBuffer = 0x4000;
if (::WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, lpnr, &hEnum) == 0) {
if ((lpnr = (LPNETRESOURCE)::GlobalAlloc(GPTR, cbBuffer)) != NULL) {
while (::WNetEnumResource(hEnum, &cEntries, lpnr, &cbBuffer) == 0) {
for (int ctr = 0; ctr < (int)cEntries; ctr++) {
if( RESOURCEUSAGE_CONTAINER == (lpnr[ctr].dwUsage & RESOURCEUSAGE_CONTAINER ) )
EnumLocalNetwork(&lpnr[ctr]);
else {
printf(lpnr[ctr].lpRemoteName);
printf("/n");
}
}
cEntries = -1;
cbBuffer = 0x4000;
}
::GlobalFree(lpnr);
}
::WNetCloseEnum(hEnum);
}
}
int main()
{
printf("Start/n");
EnumLocalNetwork(NULL);
printf("Finish/n");
return 0;
}

How do I enumerate all of the domains, computers, and shares on a Windows network?

#include <winnetwk.h>
#pragma comment (lib, "mpr")
//by MSDN
BOOL WINAPI EnumerateFunc (LPNETRESOURCE lpnr)
{
HANDLE hEnum;

DWORD dwIndex,
dwResult,
dwBufferSize = 16384,
dwNumEntries = 0xFFFFFFFF; // Enumerate all possible entries.

LPNETRESOURCE lpnrLocal; // Pointer to enumerated structures.

dwResult = WNetOpenEnum (
RESOURCE_GLOBALNET, // All resources on the network
RESOURCETYPE_ANY, // All resources
0, // Enumerate all resources.
lpnr, // The container to enumerate
&hEnum); // Handle to resource

if (dwResult != ERROR_SUCCESS)
{
return FALSE;
}

// Allocate memory for NETRESOURCE structures.
if (!(lpnrLocal = (LPNETRESOURCE) LocalAlloc (LPTR, dwBufferSize)))
return FALSE;

do
{
dwResult = WNetEnumResource (
hEnum, // Resource handle
&dwNumEntries, // Number of entries
lpnrLocal, // LPNETRESOURCE
&dwBufferSize); // Buffer size

if (dwResult == ERROR_SUCCESS)
{
for (dwIndex = 0; dwIndex < dwNumEntries; dwIndex++)
{
// Insert code here to perform operations with lpnrLocal
// for example, to display contents of NETRESOURCE structures.
// ...
wprintf(lpnrLocal[dwIndex].lpRemoteName);
printf("/n");
// If this NETRESOURCE is a container, call the function
// recursively.
if (RESOURCEUSAGE_CONTAINER ==
(lpnrLocal[dwIndex].dwUsage & RESOURCEUSAGE_CONTAINER))
{
if(!EnumerateFunc (&lpnrLocal[dwIndex]))
return 0;
}
}
}
else if (dwResult != ERROR_NO_MORE_ITEMS)
{
return false;
break;
}
} while (dwResult != ERROR_NO_MORE_ITEMS);

LocalFree (lpnrLocal);

dwResult = WNetCloseEnum (hEnum);

if (dwResult != ERROR_SUCCESS)
{
return FALSE;
}
return TRUE;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值