Introduction
Have you ever seen functions by name EnumFunctions? Like EnumWindows etc. Have you ever wondered how they are created? In this article, we will create a simple one! Just be relaxed and read this article to EOF!
What is an enum function?
These types of functions are ...!?! Let me explain like this: assume that you have some fruits. OK? Some apples, oranges, and bananas. You are searching for apples. And, for each apple you can find, you will shout: "Hey I found another apple!" This is the role of this type of functions: for each element, return something.
Let's start
Declaring an EnumFunction is simple. First, you should have a variable type to tell the function what kind of function is the input. See this code snippet (declarations in the header file):
typedef BOOL (CALLBACK*YOURPROCTYPE)(FirstType,SecondType,...);
Now see mine:
typedef BOOL (CALLBACK*MYPROC)(LPCTSTR);
And for declaring the EnumFunction
:
ReturnType WINAPI EnumFunction(YOURPROCTYPE lpProcname,arg-list,…);
And mine:
BOOL WINAPI EnumFunc(MYPROC lpProc);
EnumFunc
passes the parameters to a callback function:
ReturnType CALLBACK yourProcName(FirstType,SecondType,...);
Note that the argument list of this callback function must be what you give in YOURPROCTYPE:
BOOL CALLBACK MyProc (LPCTSTR prompt);
Here are my sample code declarations:
typedef BOOL (CALLBACK*FILESPROC)(LPCTSTR);
void WINAPI EnumFiles(FILESPROC lpEnumFiles,LPCTSTR lpszFileName);
int CALLBACK EnumFilesProc (LPCTSTR lpszFileName);
And here goes the EnumFiles
function. Its task is to find the files in the given path, and for each file, calls the callback function:
void WINAPI EnumFiles(FILESPROC lpEnumFiles,LPCTSTR lpszFileName)
{
CString nfle;
numoffiles=0;
CFileFind file;
BOOL bFind=file.FindFile(lpszFileName,NULL); while (bFind) {
bFind=file.FindNextFile(); numoffiles=lpEnumFiles(file.GetFileName()); }
nfle.Format("%d Files found",numoffiles);
AfxMessageBox(nfle); }
BOOL CALLBACK EnumFilesProc(LPCTSTR lpszFileName)
{
numoffiles++;
list->InsertString(list->GetCount(),lpszFileName);
return numoffiles;
}
Now for calling the EunmFunction
, you only need to write some code:
list->ResetContent();
EnumFiles(EnumFilesProc,"C:\\*.exe");
In this source code, we will get a path and enumerate all the files in the path! I use this enumeration technique to get all the sections in an INI file, and you can do anything you want! Any opinions and comments are welcome. Or questions maybe..