VisualCpp.org Collection of Visual C++ Stuffs

26Jun/080

Getting benefit of WaitForMultiple Object?

WaitForMultipleObject could be used to synchronize the calls/events. Let take an example, we have to print something; we need a document and printer should be ready to take job. Now for document printer to print same document need to satisfy above two conditions, document must be present and printer should be ready, then only it could start the printing job. So, document printing application must wait till both of condition satisfies, i.e. it waits for event. Here we can utilize WaitForMultipleObject, it  could help the mainthread to wait till other event is complete.

Main Thread:-

  hEvent[0] = CreateEvent(NULL,FALSE,FALSE,"EVENTONE");
  hEvent[1] = CreateEvent(NULL,FALSE,FALSE,"EVENTTWO");
  // our two worker thread, who will set event for main event:-
  AfxBeginThread(LpThreadWorker,(LPVOID)hEvent[0]);
  AfxBeginThread(LpThreadWorker,(LPVOID)hEvent[1]);

// Waiting thread
  AfxBeginThread(LpThreadMaster,(LPVOID)hEvent);

LpThreadWorker : -

UINT LpThreadWorker (LPVOID lParam)
{
 AfxMessageBox("From Thread");
 HANDLE hHandle = static_cast<HANDLE>(lParam);
 SetEvent(hHandle);

return 0;
}

LpThreadMaster : -

UINT LpThreadMaster (LPVOID lParam)
{
  HANDLE* hHandle = static_cast<HANDLE*>(lParam);
  WaitForMultipleObjects(2,hHandle,true,INFINITE);

AfxMessageBox("From Thread complete");
  CloseHandle(hHandle[0]);
  CloseHandle(hHandle[1]);
  return 0;
}

Executing above code:
1. When main thread starts, all worker thread get started, two threads are blocked by MessageBox and one thread is waiting for event to occur from different thread.


2. whenever  user click on Ok button of  MessageBox, the event is set and once all event for whom WaitForMultipleObject is waiting are set, it will succeed and another message box is displayed showing success.

Filed under: General, System, Win32 No Comments
21Jun/08Off

Closing the application gracefully from other application?

There are numerous method to close the application from different application, some of them I have listed here!.

  • Send WM_SYSCOMMAND specifying the SC_CLOSE as parameter, this work same way as ALT+F4 works. I have used the FindWindow api to find window HWND of target window. In example it is Notepad app ( to know more about FindWindow, click here )

    CWnd *NtWnd = FindWindow(L"Notepad",NULL);
    NtWnd->PostMessage(WM_SYSCOMMAND,SC_CLOSE,0);

  • Use SendInput api to send to simulate the ALT+F4.

//send the ALT key message

INPUT inputStuctAlt,inputStuctF4;
inputStuctAlt.type = INPUT_KEYBOARD;
inputStuctAlt.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
inputStuctAlt.ki.dwExtraInfo = 0;
inputStuctAlt.ki.wScan = 0x12;//
inputStuctAlt.ki.wVk=VK_MENU;
inputStuctAlt.ki.time = GetTickCount();

SendInput(1,&inputStuctAlt,sizeof(inputStuctAlt));

//send the F4 down key message
inputStuctF4.type = INPUT_KEYBOARD;
inputStuctF4.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
inputStuctF4.ki.dwExtraInfo = 0;
inputStuctF4.ki.wScan =VK_F4;//
inputStuctF4.ki.wVk=VK_MENU;
inputStuctF4.ki.time = GetTickCount();
SendInput(1,&inputStuctF4,sizeof(inputStuctF4));

//send the F4 up key message
inputStuctF4.ki.dwFlags = KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP;
inputStuctF4.ki.time = GetTickCount();
SendInput(1,&inputStuctF4,sizeof(inputStuctF4));

//send the ALT up key message
inputStuctAlt.ki.dwFlags = KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP;
inputStuctAlt.ki.time = GetTickCount();
SendInput(1,&inputStuctF4,sizeof(inputStuctF4));

Filed under: General, System, Win32 Comments Off
21Jun/08Off

Closing the application gracefully from other application?

There are numerous method to close the application from different application, some of them I have listed here!.

  • Send WM_SYSCOMMAND specifying the SC_CLOSE as parameter, this work same way as ALT+F4 works. I have used the FindWindow api to find window HWND of target window. In example it is Notepad app ( to know more about FindWindow, click here )

    CWnd *NtWnd = FindWindow(L"Notepad",NULL);
    NtWnd->PostMessage(WM_SYSCOMMAND,SC_CLOSE,0);

  • Use SendInput api to send to simulate the ALT+F4.

//send the ALT key message

INPUT inputStuctAlt,inputStuctF4;
inputStuctAlt.type = INPUT_KEYBOARD;
inputStuctAlt.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
inputStuctAlt.ki.dwExtraInfo = 0;
inputStuctAlt.ki.wScan = 0x12;//
inputStuctAlt.ki.wVk=VK_MENU;
inputStuctAlt.ki.time = GetTickCount();

SendInput(1,&inputStuctAlt,sizeof(inputStuctAlt));

//send the F4 down key message
inputStuctF4.type = INPUT_KEYBOARD;
inputStuctF4.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
inputStuctF4.ki.dwExtraInfo = 0;
inputStuctF4.ki.wScan =VK_F4;//
inputStuctF4.ki.wVk=VK_MENU;
inputStuctF4.ki.time = GetTickCount();
SendInput(1,&inputStuctF4,sizeof(inputStuctF4));

//send the F4 up key message
inputStuctF4.ki.dwFlags = KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP;
inputStuctF4.ki.time = GetTickCount();
SendInput(1,&inputStuctF4,sizeof(inputStuctF4));

//send the ALT up key message
inputStuctAlt.ki.dwFlags = KEYEVENTF_EXTENDEDKEY|KEYEVENTF_KEYUP;
inputStuctAlt.ki.time = GetTickCount();
SendInput(1,&inputStuctF4,sizeof(inputStuctF4));

Filed under: General, System, Win32 Comments Off
16Jun/08Off

Getting and Setting volume of audio wave device?

Now after retrieving the device information, now let do some advance stuff, like getting and setting volume of device. I have used waveOutOpen, waveOutGetVolume and waveOutSetVolume api for setting and getting volume of audio device.

HWAVEOUT hWaveOut = NULL;
WAVEFORMATEX pcmWaveFormat = {0};
MMRESULT mResult = 0;

//fill oru wave structure
pcmWaveFormat.wFormatTag = WAVE_FORMAT_PCM;
pcmWaveFormat.nChannels = 1;
pcmWaveFormat.nSamplesPerSec = 11025L;
pcmWaveFormat.nAvgBytesPerSec = 11025L;
pcmWaveFormat.nBlockAlign = 1;
pcmWaveFormat.wBitsPerSample = 8;
pcmWaveFormat.cbSize = 0;

if( (mResult = waveOutOpen(&hWaveOut,0,&pcmWaveFormat,0,0,0)) == MMSYSERR_NOERROR)
{
DWORD dwVolume = 0;
waveOutGetVolume(hWaveOut, &dwVolume);
dwVolume += 1;
waveOutSetVolume(hWaveOut, dwVolume);
}
else
{
switch(mResult)
{
case MMSYSERR_ALLOCATED:
MessageBox("Specified resource is already allocated.");
break;
case MMSYSERR_BADDEVICEID:
MessageBox("Specified device identifier is out of range.");
break;
case MMSYSERR_NODRIVER:
MessageBox("No device driver is present.");
break;
case MMSYSERR_NOMEM:
MessageBox("Unable to allocate or lock memory.");
break;
case WAVERR_BADFORMAT:
MessageBox("Attempted to open with an unsupported waveform-audio format.");
break;
case WAVERR_SYNC:
MessageBox("The device is synchronous but waveOutOpen was called without using the WAVE_ALLOWSYNC flag.");
break;
}
}

Step:
1. Fill the WAVEFORMATEX with type of format you need, and no of audio channel you required
2. Call waveOutOpen function to retrieve the handle to audio waveout
3. call waveOutGetVolume to get current volume level
4. call waveOutSetVolume to set current volume level

11Jun/08Off

Getting audio device information?

Retrieving the audio device information is useful for display purposes or somebody is coding audio specific application. Last post I have you already let you know about waveOutGetNumDevs api, which bring the number of output based audio device present in the system. For getting information regarding the audio device driver we have make call to waveOutGetDevCaps with WAVEOUTCAPS as returnable argument.

If function is successful, it will fill WAVEOUTCAPS structure with device details.


 unsigned int iNumAudDevs = waveOutGetNumDevs();

//Get Device informations
 for(UINT iCount = 0 ;
  iCount < iNumAudDevs;
  iCount ++  )
 {
  WAVEOUTCAPS wCaps = {0};
  MMRESULT mResult = 0;
  //Get information of First audio device!
  mResult = waveOutGetDevCaps(iCount,&wCaps,sizeof(wCaps));

if( mResult != MMSYSERR_NOERROR)
  {
  // make user aware, they have provided some wrong details
  switch(mResult)
  {
  case MMSYSERR_BADDEVICEID:
  MessageBox("Specified device identifier is out of range.");
  break;

case MMSYSERR_NODRIVER:
  MessageBox("No device driver is present.");
  break;

case MMSYSERR_NOMEM:
  MessageBox("Unable to allocate or lock memory.");
  break;
  }
  }
  else
  // Publish the device name
  {
  MessageBox(wCaps.szPname,"Window Audio Name");

}

 }

please again I am mentioning don’t forget to include MMSystem.h and winmm.lib in your project.

Filed under: WindowMedia Comments Off
6Jun/08Off

How can I check, wheather audio driver is present in PC?

Window api’s are really very useful and vast, so you have to dive in ocean of api’s, to find the correct api. waveOutGetNumDevs could help you to check whether there is any audio system present in the system or not, also it return you with number of  audio device present in the system.

unsigned int iNumAudDevice = waveOutGetNumDevs();

Please don’t forget to include MMSystem.h and winmm.lib in the project

4Jun/082

Getting Folder path and FileName at runtime

While you coding you must have encountered situation to retrieve the current directory  or executable name at run time. As some of executable are independent / doesn't attached to any particular directory. So for precautionary measure, it should be consider good programming practice, if you find the  said information on run time, the benefits includes, hard coding folder path or crash occurring due to non existent folder location.

Here is code which do that,:-

CStringszCurrentDirectory , szFileName , szTempString;
TCHARszModulePath[_MAX_PATH] = {0};

DWORD dw = GetModuleFileName(NULL /*Current Module*/,
  szModulePath,
  MAX_PATH);

if( dw > 0) // Something is returned from the call of API.
{
 szTempString = szModulePath;
 // Find the position of last backspace
 int iBackSlashPos = szTempString.ReverseFind('\\');

 szCurrentDirectory = szTempString.Left(iBackSlashPos);
 szFileName = szTempString.Right((szTempString.GetLength() - iBackSlashPos) - 1 /*  Extra One for removing additional backspace*/);
}

Algorithms (Not perfect, but working at least):-

  • We give call to GetModuleFileName Api, passing NULL (for current module), which will return current executable path in it second parameter (szModulePath in above case).
  • We will convert the normal character array into CString object, for easier string manipulation, as it has many handy functions for string manipulation. 
  • Now we try to retrieve the last Backslash, as you must be aware, folder and filenames are separated by backslash, and after backslash the file path contain the filename.
  • Based on above fact we can easily get the current directory and filename, by seaching and retrieving part of string we are interested in . 
Filed under: General, MFC, System 2 Comments