Showing posts with label MSDN. Show all posts
Showing posts with label MSDN. Show all posts

Wednesday, December 15, 2010

Simulating keypress

The following code will allow you to simulate the keypress of the keyboard.
This function accepts a string to simulate typing them. It will press the Enter key at the end of the simulation. The code will handle pressing of the "Shift" key when needed.

C++ Source code. MFC.

===============


void SendKeypress(CString strText)
{
int len, i;
char c;
len = strText.GetLength();
for (i = 0; i < len; i++) {
c = strText[i];
WORD vkey = VkKeyScan(c);
WORD shift = HIBYTE(vkey);
BYTE scan = MapVirtualKey(vkey, 0);
if (shift) {
keybd_event(VK_SHIFT, MapVirtualKey(VK_SHIFT,0), 0, 0);
}
keybd_event(vkey, scan, 0, 0);
keybd_event(vkey, scan, KEYEVENTF_KEYUP, 0);
if (shift) {
keybd_event(VK_SHIFT, MapVirtualKey(VK_SHIFT,0), KEYEVENTF_KEYUP, 0);
}
}
// Press "Enter"
keybd_event(VK_RETURN, 0x1c, 0 , 0);
keybd_event(VK_RETURN, 0x9c, KEYEVENTF_KEYUP, 0);
}

Simulate clicking of mouse buttons

The following code allows you to simulate clicking of the mouse button programmatically.
It will remember the current cursor position, move to the coordinate to click, perform the click and restore the cursor position.

C++ source code.

===============

void ClickOnPoint(int x, int y)
{
POINT prevPt;
GetCursorPos(&prevPt);
SetCursorPos(x, y);

mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);

SetCursorPos(prevPt.x, prevPt.y);
}

Check whether a file exist in C++

The following code allows you do check whether a particular file exist.

C++ source code. Using Shell API.

=======

BOOL CheckFileExist(LPCTSTR lpszFullPathName)
{
BOOL bResult = FALSE;
SHFILEINFO shfileinfo;
if (SHGetFileInfo(lpszFullPathName, 0, &shfileinfo, sizeof(SHFILEINFO), SHGFI_DISPLAYNAME) != 0) {
// File Exist
bResult = TRUE;
}
return bResult;
}