Windows APIs

How to check whether the window handle is valid?

2


Since communication by messages are so easy, windows used to communicate with each other by using messages. For instance, if simple data blocks are to be transfered – WM_COPYDATA can be used. For all those instances the window should be alive. But how to know whether the current window handle is valid or whether it points to a dead window?


You can call the api – IsWindow() by passing window handle. If the handle points to a live window, then the function returns true else false. Have a look at the code snippet.

// The handle to be tested.
HWND hWindow = GetSafeHwnd();

// Check whether the window is still there.
BOOL bWindowAlive = IsWindow( hWindow );


While digging for the api, i found an interesting info. What about window handle re-cycling? For instance you have a window handle and you’re going to check that window by calling IsWindow() function. But in between that the real window is closed and a new window is created. Whether the window handler will be allocated to the new window?

Well, the answer is here. Have a look at it. Its interesting. The oldnewthing. ;)


Targeted Audience – Beginners.

How to hide file programmatically?

3


Hidden files are very basic and primitive mode of protection. If your file is set as hidden, it won’t get listed to normal user, unless he explicitly enabled – “Show hidden files”. Well, how to make a file really hidden?


You can use the api – SetFileAttributes(). Pass FILE_ATTRIBUTE_HIDDEN as attribute and you’re file will be hidden. Have a look at the code snippet.

// The file, which is to be hidden.
CString csFile = _T("C:\\Autumn Leaves.jpg");

// Hide the file.
SetFileAttributes( csFile, FILE_ATTRIBUTE_HIDDEN );


Another alternative is to use CFile::SetStatus(). Have a look at it too…


Targeted Audience – Beginners.

How to handle F1 or help in application?

0


Help is inevitable part of every windows application. The first function key – F1 itself is assigned as help in every application. Well, how to handle the user’s “Mayday” call in application?


Basically you’ve to handle the WM_HELP message. When you press F1 the WM_HELP message will be posted to your window. To handle this via MFC, Add ON_WM_HELPINFO() to message map and implement OnHelpInfo() in your dialog. Have a look at the following code snippet.

// Add ON_WM_HELPINFO() to your message map.
BEGIN_MESSAGE_MAP(CYourDialog, CDialog)
   ...
   ON_WM_HELPINFO()
END_MESSAGE_MAP()

// Add this function to your dialog.
BOOL CYourDialog::OnHelpInfo( HELPINFO* HelpInfo)
{
   // Handle your help request here.
   return TRUE;
}


Well, the only help i used to use is MSDN. If I accidentally launch Windows help, I’ll kill it immediately by using taskmgr. I don’t know why I hate it. :)


Targeted Audience – Beginners.

How to parse the parent directory from a given path – More easily?

0


Yesterday one of my friend called me to solve the mystery behind his crash! When i checked the code, i saw a couple of string operations by pointers, memory allocations, memset - All evils under one hood. :) Actually the memset caused the crash which writes beyond the buffer and corrupt other stack objects.

But suddenly i noticed one thing – what he is trying to do? He have a path and he wants to get the parent path. E.g. If his path is “C:\Application\Config”, then he want to get - “C:\Application” the just parent path. Well, the guy brushed up old string lessons and handled everything by himself which resulted in crash. I reviled him a secret api to do the stuff painlessly. Mmmm… I can tell that secret to you too…


The api is – PathRemoveFileSpec(). You can use it to remove the last directory or filename from the given path. Have a look at the code snippet.

#include "Shlwapi.h"
...
// Main path.
TCHAR pBinPath[] = _T("C:\\MyApplication\\bin");

// Get the parent path.
PathRemoveFileSpec( pBinPath );

// Now the pBinPath contains - "C:\\MyApplication"


Don’t forget to add Shlwapi.lib to project settings. ;)


Targeted Audience – Beginners.

How to add user to system programmatically?

0


I still remember, during my first computer course( DOS, Windows 3.1 and BASIC) the machine login names provided were like this – s1,s2… etc. I think they’ve used some kind of scripts to generate login for whole 50 students. if they create all users manually, it might take a lot of time.

Well, now I’m grown up and just thought about those old days – How they might added the users by script? Can i do the same in my modern windows box programmatically?


You can use the api – NetUserAdd(). See the code snippet.

#include "Lm.h"
...
// New User information.
USER_INFO_1 UserInfo;
UserInfo.usri1_name = L"WeSeeTips";       // User Name
UserInfo.usri1_password = L"ThatsSecret"; // Password.

UserInfo.usri1_priv = USER_PRIV_USER; // Normal User.
UserInfo.usri1_flags = UF_SCRIPT;

UserInfo.usri1_home_dir = 0;    // Home Directory.
UserInfo.usri1_comment = 0;     // User comment.
UserInfo.usri1_script_path = 0; // Path of script.

// Add the new user.
DWORD Error = 0;
NetUserAdd( 0,  // Local machine.
            1,  // User info level.
            (BYTE*)&UserInfo, // User info.
            &Error ); // Error code.


Well, don’t forget to add Netapi32.lib to project settings.


Targeted Audience – Intermediate.

How to handle system power change notifications?

2


Today i was watching one movie a in HP QuickPlay application. In the mean while, the playback suddenly stopped and it showed a messagebox that the battery is running out.

At that moment i noticed that i didn’t connected the power cord. But how did the application identified the battery is critical?


When the power status changes the system broadcast the message – WM_POWERBROADCAST. Just handle the message and you’ll get notified about power related events. Have a look at the code snippet.

For handling the message, modify the message map as follows.

BEGIN_MESSAGE_MAP(CDialogDlg, CDialog)
...
ON_MESSAGE( WM_POWERBROADCAST, OnPowerBroadcast )
END_MESSAGE_MAP()

Now add function – LRESULT OnPowerBroadcast( WPARAM wParam, LPARAM lParam ) to your dialog class with body as follows.

// Handle Power Event Notifications.
LRESULT CDialogDlg::OnPowerBroadcast( WPARAM wParam,
                                      LPARAM lParam )
{
    // Check whether the battery is low.
    if( PBT_APMBATTERYLOW == wParam )
    {
        // Yes. So shut down the operations.
    }
    return TRUE;
}

There are a lot more notification other than PBT_APMBATTERYLOW that you can check. They are -

  • PBT_APMBATTERYLOW – Battery power is low.
  • PBT_APMOEMEVENT – OEM-defined event occurred.
  • PBT_APMPOWERSTATUSCHANGE – Power status has changed.
  • PBT_APMQUERYSUSPEND – Request for permission to suspend.
  • PBT_APMQUERYSUSPENDFAILED – Suspension request denied.
  • PBT_APMRESUMEAUTOMATIC – Operation resuming automatically after event.
  • PBT_APMRESUMECRITICAL – Operation resuming after critical suspension.
  • PBT_APMRESUMESUSPEND – Operation resuming after suspension.
  • PBT_APMSUSPEND – System is suspending operation.


Well, don’t ask me – “Which movie you was keenly watching?” ;)


Targeted Audience – Beginners.

How to get Kernel time usage and User time usage of process?

0


Every process spend its time in kernel space as well as in user space. You can watch it by using perfmon.exe. Have a look at the screenshot.

But how to get the Kernel time and user time of a particular process?


You can use the api – GetProcessTimes(). See the code snippet below,

FILETIME CreationTime = { 0 };
FILETIME ExitTime     = { 0 };
FILETIME KernelTime   = { 0 };
FILETIME UserTime     = { 0 };

// Get Process times.
GetProcessTimes( GetCurrentProcess(),
                 &CreationTime,
                 &ExitTime,
                 &KernelTime,
                 &UserTime );

// Format time to readable form.
SYSTEMTIME SystemTime = { 0 };
FileTimeToSystemTime( &KernelTime, & SystemTime );

// Kernel Time in HH:MM:SS:mmm.
CString csKernelTime;
csKernelTime.Format( _T("Kernel Time - %02d:%02d:%02d:%04d"),
                     SystemTime.wHour,
                     SystemTime.wMinute,
                     SystemTime.wSecond,
                     SystemTime.wMilliseconds );

// Format user time to readable form.
FileTimeToSystemTime( &UserTime, & SystemTime );

// Kernel Time in HH:MM:SS:mmm.
CString csUserTime;
csUserTime.Format( _T("User Time - %02d:%02d:%02d:%04d"),
                   SystemTime.wHour,
                   SystemTime.wMinute,
                   SystemTime.wSecond,
                   SystemTime.wMilliseconds );


You can also get the process creation time and process exit time by using the same api.


Targeted Audience – Beginners.

How to swap the mouse buttons Programmatically?

2


In our world, 87 percentage of population is right handed. Left handedness is so uncommon that the left handed population is about 13% only. But Microsoft have already taken care about the whole world, where you can choose the mouse to be left handed or right handed. See the mouse control panel screenshot.

But how can you do it programmatically?


Well, you can use the api – SwapMouseButton(). If you pass TRUE, then the mouse buttons will get swapped for a left handed person. If you pass FALSE, then the mouse buttons will be reset back for right hand use. See the code snippet.

// Swap mouse buttons for left hand use
SwapMouseButton( TRUE );

// Reset mouse buttons for right hand use
SwapMouseButton( FALSE );


Do you know that left handed guys can think in multi threaded where right hand guys can think only sequentially. have a look at Wiki. Its interesting. ;)


Targeted Audience – Beginners

How to locate the process which owns the window by using window handle?

0


“Goto Process” menu item in Task Manager is one of the frequently used stuff. isn’t it? ;) Its shows a list of windows currently displayed in desktop and by using “Goto Process”, we can find the process which owns the window. Have a look at it and feel refreshed! Ever thought of doing the same? How can we identify the process which owns the window by using window handle?


You can use the api – GetWindowThreadProcessId(). If you provide the window handle, if will return back the Id of the process which owns that window. Have a look at code snippet.

// Get the Id of Process which owns Windows Desktop.
DWORD dwProcessId = 0;
GetWindowThreadProcessId( ::GetDesktopWindow(),
                          &dwProcessId );


Pretty good! nah? ;)


Targeted Audience – Intermediate.

How to check whether a file exists of not?

2


While reading configuration file, while reading some setting file, every where we’ve to check whether the file exists or not before opening and starts reading. The simple technique is to open the file by using file apis or to search for the file by using FindFirstFile(). Or is there any simple api to do so?


You can use the api – PathFileExists(). Check the following code snippet.

#include "shlwapi.h"
...
// File path.
CString csFile = _T( "C:\\Autumn Leaves.jpg");

if( PathFileExists( csFile ))
{
    // Yes! the file exists.
}


Don’t forget to add shlwapi.lib to your project settings. ;)


Targeted Audience – Beginners.

Go to Top