Code Repo    |     RSS
MD's Technical Sharing



Tuesday, March 24, 2009

Enumerate through all files in a folder

This can be achieved easily using the Win32 APIs FindFirstFile and FindNextFile


WIN32_FIND_DATAW FindFileData;

//find the first file matching the pattern

HANDLE hFind = FindFirstFile(L"\\My Documents\\*.jpg", &FindFileData);

//find the first file, continue to find next file

if (hFind != INVALID_HANDLE_VALUE)

{

printf("%S", FindFileData.cFileName);

while (FindNextFile(hFind, &FindFileData) != 0)

{

}

FindClose(hFind);

}

Read More »

Thursday, March 19, 2009

Open a file with its default viewer:

The following will open a file with its default viewer. The behaviour is exactly the same as what will happen when you double click on that file in Explorer.

SHELLEXECUTEINFO lpExecInfo;
memset(&lpExecInfo, 0, sizeof(SHELLEXECUTEINFO));
lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
//name of file to open. For URL, it will be open in the default browser
lpExecInfo.lpFile = L"doc1.doc";
lpExecInfo.lpParameters = _T("");
lpExecInfo.lpDirectory = _T("");
lpExecInfo.lpVerb = _T("open");
lpExecInfo.fMask = 0;
lpExecInfo.hwnd = g_hwnd; //handle of current window
lpExecInfo.hInstApp = g_hinstModule; //handle to current executable
if (!ShellExecuteEx(&lpExecInfo))
{
//cannot run, show error here
}

Alternatively, use the following to use any program to open a particular file:

PROCESS_INFORMATION pi = {0};
if (!CreateProcess(L"notepad.exe", L"readme.txt", NULL, NULL, NULL, 0, NULL, NULL, NULL, &pi))
printf("Cannot execute process \n");
else
WaitForSingleObject(pi.hProcess, INFINITE);

Read More »

Saturday, March 14, 2009

Allow only digits in textbox

The following code apply ES_NUMBER to allow only digits to be typed into the edit control.


Public Const GWL_STYLE As Int32 = (-16)
Public Const ES_NUMBER As Int32 = &H2000


<DllImport("User32.dll", EntryPoint:="GetWindowLong")> _
Public Function GetWindowLong(ByVal window As IntPtr, ByVal index As Int32) As Int32
End Function


<DllImport("User32.dll", EntryPoint:="GetWindowLong")> _
Public Function SetWindowLong(ByVal window As IntPtr, ByVal nIndex As Int32, ByVal dwNewLong As Int32) As Int32
End Function

'accept only digit in the specified textbox
Public Sub SetNumericInputMode(ByVal txtBox As TextBox)
Dim style As Int32 = GetWindowLong(txtBox.Handle, GWL_STYLE)
SetWindowLong(txtBox.Handle, GWL_STYLE, style
Or ES_NUMBER)
End Sub

Read More »

Monday, February 16, 2009

Draw an icon from resource

g_hIcon = (HICON)LoadImage((HINSTANCE)GetModuleHandle(IMAGENAME), MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);

DrawIcon(hdc, left, top, g_hIcon);


IMAGENAME is the name the the current DLL/EXE file. The icon must be created using VS resource editor and its ID set to IDI_ICON1

Read More »

Sunday, January 11, 2009

MessageBox with Help button

Showing a four-button message box with the default set to the fourth button:


int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstPrev,
LPSTR lpCmdLine, int nShowCmd)
{
return MessageBox(NULL, TEXT("Four buttons!"), TEXT("Title"), MB_ABORTRETRYIGNORE | MB_HELP | MB_DEFBUTTON4);
}


Clicking on the Help button (MB_HELP) is documented as sending a WM_HELP message to your program. Since there is nothing to catch that message, it does nothing. The other buttons return the ID value of that button, dismissing the message box.


Reference:

msdn.com/oldnewthing/archive/2008/12/19/9239267.aspx

Read More »

Tuesday, November 4, 2008

Distinguish between different Windows versions

1. Check if Environment.OSVesion.Platform returns WIN32NT (for Win3.1, Win95, Win98, WinME) or WIN32Windows (for WinNT and later) or WinCE (for Windos Mobile etc.)


2. Check version from Envirnement.OSVersion.Version

Win95: 4.0

Win98: 4.10

WinME: 4.90

NT 3.5: 3.51

NT 4.0: 4.0

Win2000: 5.0

WinXP: 5.1

Win2000: 5.2

Vista/Windows Server 2008: 6.0

Windows Mobile 5: Windows CE 5.1

Windows Mobile 6: Windows CE 5.2


Reference:

http://www.vb-helper.com/howto_net_os_version.html

Read More »

Monday, October 13, 2008

Kill a process given its executable name.

BOOL KillProcessByName(const TCHAR* p_strEXE)
{
printf("Attempting to terminate ");
OutputDebugString(p_strEXE);
printf("\n");

HANDLE hSnapShot
= NULL;
PROCESSENTRY32 pEntry
= {0};

// Get the snapshot of the system
hSnapShot
= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (hSnapShot != INVALID_HANDLE_VALUE)
{
pEntry
.dwSize = sizeof(pEntry);

//Get first process
if (Process32First(hSnapShot, &pEntry))
{
TCHAR strTempExe
[MAX_PATH];
_tcscpy(strTempExe, pEntry.szExeFile);

printf("Found: ");
OutputDebugString(strTempExe);
printf("\n");

//found process on the first attempt, kill it
if (_tcscmp(strTempExe, p_strEXE) == 0) goto KillProcess;

//Iterate through all other processes
while (Process32Next(hSnapShot, &pEntry))
{
_tcscpy(strTempExe, pEntry.szExeFile);

printf("Found: ");
OutputDebugString(pEntry.szExeFile);
printf("\n");

//we have found our process;
if (_tcscmp(strTempExe, p_strEXE) == 0) goto KillProcess;
}
}
else
{
printf("Process32First FAILED. Error %d\n", GetLastError());
}
}
else
{
printf("Process32First FAILED. Error %d\n", GetLastError());
}

//if we are here it means process cannot be found;
goto ProcessNotFound;

KillProcess:

CloseHandle(hSnapShot);

//kill it
HANDLE hProcess
= OpenProcess(PROCESS_ALL_ACCESS, FALSE, pEntry.th32ProcessID);
if (hProcess)
{
if (::TerminateProcess(hProcess, 0))
{
printf("Process terminated.\n");
return TRUE;
}
else
{
printf("TerminateProcess FAILED. Error %d\n", GetLastError());
return FALSE;
}
}
else
{
printf("OpenProcess FAILED. Error %d\n", GetLastError());
return FALSE;
}

ProcessNotFound:
CloseHandle(hSnapShot);

printf("Specified process not found.\n");
return FALSE;
}

Read More »

Saturday, July 12, 2008

Display a dialog box retrieved from resource

To display a dialog created via Visual Studio Resource editor, use the DialogBox function. Assuming the dialog box resource name is IDD_DIALOG1:

int dlgResult = DialogBox(g_hinstModule, MAKEINTRESOURCE(IDD_DIALOG1), hwnd, (DLGPROC) DlgCallbackProc);

When an event occurs in a dialog box control, the control sends a WM_COMMAND message to the dialog box procedure. The high-order word of the wParam parameter is a notification code, indicating the type of event that occurred. The low-order word of wParam is a constant identifying the control. The lParam parameter is the window handle for the control.

To close the dialog box, call EndDialog. The second parameter of EndDialog will be the return value of the blocking call to DialogBoxW, which is dlgResult in the above code.

BOOL CALLBACK DlgCallbackProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
//occurs when dialog box was initialized

case WM_COMMAND:
//when a control receives action
switch (LOWORD(wParam)) //ID of the control
{
case IDR_MENUITEM1:
//a menu item was pressed. Pass IDR_MENUITEM1 to indicate that the ACCEPT menu has been clicked
EndDialog(hwndDlg, IDR_MENUITEM1);
break;
}

break;
}
return FALSE;
}

g_hinstModule is the handle to the executable containing the resource.

Reference:
http://win32.freetechsecrets.com/WIN32Processing_the_WMCOMMAND_Message.htm
Read More »