Search This Blog

Tuesday, December 15, 2009

Linker Errors when using winservice

Some times we will get linker errors like below when creating winservice.
To solve this add following code.



#pragma comment (lib, "advapi32.lib")
#pragma comment (lib, "user32.lib")


Or

include user32.lib and advapi32.lib in linker input of project settings



error LNK2019: unresolved external symbol __imp__CloseServiceHandle@4 referenced in function
error LNK2019: unresolved external symbol __imp__CreateServiceA@52 referenced in function
error LNK2019: unresolved external symbol __imp__OpenSCManagerA@12 referenced in function
error LNK2019: unresolved external symbol __imp__DeleteService@4 referenced in function
error LNK2019: unresolved external symbol __imp__OpenServiceA@12 referenced in function
error LNK2019: unresolved external symbol __imp__ControlService@12 referenced in function
error LNK2019: unresolved external symbol __imp__StartServiceA@12 referenced in function
error LNK2019: unresolved external symbol __imp__StartServiceCtrlDispatcherA@4 referenced in function
error LNK2019: unresolved external symbol __imp__SetServiceStatus@8 referenced in function
error LNK2019: unresolved external symbol __imp__RegisterServiceCtrlHandlerA@8 referenced in function
error LNK2019: unresolved external symbol __imp__PostThreadMessageA@16 referenced in function

Wednesday, December 2, 2009

Remove Duplicates From Vector Template Example



#include <vector>
#include <algorithm>
using namespace std;
// Add this header files

/*
Template function to Remove Duplicates
From a vector */


template <class T>
void RemoveDuplicates(vector<T> &vecContents)
{
vector<T> ::iterator vItr;

sort(vecContents.begin(),vecContents.end());
vItr=unique(vecContents.begin(),vecContents.end());
if(vItr!=vecContents.end())
vecContents.erase(vItr,vecContents.end());
}




//Usage Example 1

vector<CString> vNames;
vNames.push_back("John");
vNames.push_back("Victor");
vNames.push_back("Nancy");
vNames.push_back("William");
vNames.push_back("Nancy");

RemoveDuplicates(vNames);


//Usage Example 2
vector<int> vNos;
vNos.push_back(1);
vNos.push_back(1);
vNos.push_back(4);

RemoveDuplicates(vNos);

Sunday, November 29, 2009

String Cstring comparision



/*
string and CSting Find, mid, left funtion
Example and comparison.
*/



#include <string> //string
using namespace std; //string


string strSample,strLeft,strRight,str;
size_t pos=0;
strSample="This is my sample";

pos=strSample.find("my");
if(pos!=string::npos)
{
strLeft=strSample.substr(0,pos);
//This is

strRight=strSample.substr(pos);
//my sample

str=strSample.substr(pos+strlen("my"));
// sample
}


CString csSample,csLeft,csRight,csStr;
int nPos=-1;
csSample="This is my sample";
if( (nPos=csSample.Find("my"))>-1)
{
csLeft=csSample.Left(nPos);
//This is

csRight=csSample.Mid(nPos);
//my sample

csStr=csSample.Mid(nPos+_tcslen("my"));
// sample

}

Tuesday, November 17, 2009

DWORD to CString and CString to DWORD



//DWORD to CString
DWORD dwNumber = 1234;
CString csNumber;
csNumber.Format("%lu", dwNumber);


//CString to DWORD
DWORD dwNO;
CString csDwNumber="1234";
dwNO= atol((char*)(LPCTSTR)csDwNumber);

COM Header and lib files




/*Error 122 error LNK2019: unresolved external symbol "wchar_t * __stdcall _com_util::ConvertStringToBSTR(char const *)" (?ConvertStringToBSTR@_com_util@@YGPA_WPBD@Z
) referenced in function
"public: __thiscall _variant_t::_variant_t(char const *)"
(??0_variant_t@@QAE@PBD@Z)


Error 121 error LNK2019: unresolved external symbol "char * __stdcall _com_util::ConvertBSTRToString(wchar_t *)" (?ConvertBSTRToString@_com_util@@YGPADPA_W@Z)
referenced in function "public: char const * __thiscall _bstr_t::Data_t::GetString(void)const " (?GetString@Data_t@_bstr_t@@QBEPBDXZ)
*/


/*
Some Times when we are using COM lt will give above Linker Errors
To fix this add the following header file and library
*/



#include <comutil.h>
# pragma comment(lib, "comsuppwd.lib")

Friday, November 13, 2009

To Set a window as a topmost window



// Set a window position as a topmost window.
::SetWindowPos( GetSafeHwnd(),
HWND_TOPMOST,
0, 0, 0, 0,
SWP_NOMOVE | SWP_NOREDRAW | SWP_NOSIZE );

To set a text in Textbox using Resource ID



//To set a text in Textbox using Resource ID
//instead of CEdit member variable
  ::SetDlgItemText(GetSafeHwnd(), IDC_EDIT1, "username");

Tuesday, November 10, 2009

CDHtmlDialog crash while updating frequently



/*
when using CDHtmlDialog to navigate a page frequently
and changing content and refresh it will crash in
ieframe.dll or mshtml.dll.

To avoid crash check browser busy state
before navigating a file in CDHtmlDialog

*/


//sample code to navigating html file

void CMYDHtmlDialog::NavigateFile()
{
CString csFilePath;
csFilePath = "c:\\sample.html";

//wait for 1 second if not loaded or in busy state
if( FALSE == WaitTillLoaded (1000) )
return;

Navigate(csFilePath, NULL, NULL);

}


//sample code to wait till page lode in browser
BOOL CMYDHtmlDialog::WaitTillLoaded (int nTimeout)
{
READYSTATE result;
DWORD nFirstTick = GetTickCount ();

do
{
m_pBrowserApp->get_ReadyState (&result);

if (result != READYSTATE_COMPLETE)
Sleep (50);

if (nTimeout > 0)
{
if ((GetTickCount () - nFirstTick) > nTimeout)
break;
}
} while (result != READYSTATE_COMPLETE);

if (result == READYSTATE_COMPLETE)
return TRUE;
else
return FALSE;
}


Saturday, October 31, 2009

To view all values and size of CStringArray in watch window

In watch window, we cannot view all the elements in a CStringArray .
We can view only the first element of the CStringArray.


To View all elements Please change the following settings [For Visual Studio 2008]:
1. Open the file "c:\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\autoexp.dat" in notepad

2. Search for the line "[AutoExpand]" add the following line.

[AutoExpand]
CStringArray=size = <m_nSize> //Add this line


3. Search for the line "[Visualizer]" add the following line.

[Visualizer] //Add the below lines after this line

CStringArray{
children
(
#array
(
expr : ($e.m_pData[$i]),
size : ($e.m_nSize)
)
)
}

4. Save this file and close All Visual studio application and open again and try.

Wednesday, September 23, 2009

Finding current , previous and next date/time using COleDateTime



COleDateTime currdate;
COleDateTime prevdate;
COleDateTime nextday;
currdate = COleDateTime::GetCurrentTime();
CString csTime= currdate.Format(); //current date and time

COleDateTimeSpan span(1,0,0,0);

int nDay = currdate.GetDay(); //current day

prevdate = currdate - span;
nextday = currdate + span;

int nPrevDay = prevdate.GetDay(); //yesterday or Previous day

int nNextDay = nextday.GetDay(); //next day

Tuesday, September 22, 2009

Creating SDI application with List View



// MainFrm.h

CSplitterWnd m_splitwnd;



//MainFrm.pp
//Override OnCreateClient using properties in classview
//CLeftView and CRightView are the class should be derived from any of view class
//like CTreeView, CListView, CFormView
// Here CRightView derived from CListView

BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
// Add following Code
if(!m_splitwnd.CreateStatic(this,1,2))
return FALSE;

if(!m_splitwnd.CreateView(0,0,RUNTIME_CLASS(CLeftView),CSize(200,200),pContext) ||
!m_splitwnd.CreateView(0,1,RUNTIME_CLASS(CRightView),CSize(100,200),pContext) )
{
m_splitwnd.DestroyWindow();
return FALSE;
}
// End


return CFrameWndEx::OnCreateClient(lpcs, pContext);
}



// RightView.cpp : implementation file
//in CRightView Class add WM_CREATE message

int CRightView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CListView::OnCreate(lpCreateStruct) == -1)
return -1;

GetListCtrl().DeleteAllItems();

CListCtrl &mylist =this->GetListCtrl();

ModifyStyle(NULL, LVS_REPORT , 0);
mylist.SetExtendedStyle( mylist.GetExtendedStyle() |LVS_EX_CHECKBOXES| LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT | LVS_EX_INFOTIP | LVS_EX_TWOCLICKACTIVATE | LVS_EX_SUBITEMIMAGES );

mylist.InsertColumn(0, _T("S.No"),LVCFMT_LEFT| LVCF_TEXT);
mylist.InsertColumn(1, _T("Name"), LVCFMT_LEFT| LVCF_TEXT);
mylist.InsertColumn(2, _T("Country"), LVCFMT_LEFT| LVCF_TEXT);
mylist.SetColumnWidth(0, LVSCW_AUTOSIZE_USEHEADER);
mylist.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER);
mylist.SetColumnWidth(2, 100);

/*
mylist.InsertItem( 0, _T(""));
mylist.SetItemText( 0, 0, _T("1") );
mylist.SetItemText( 0, 1, _T("John") );
mylist.SetItemText( 0, 2, _T("India") );
*/


return 0;
}

Monday, September 21, 2009

Removing Duplicates from STL Vector


#include <vector>
#include <algorithm>
using namespace std;
// Add this header files


vector<CString> vNames;
vector<CString> ::iterator vItr;
CString csName;

vNames.push_back("John");
vNames.push_back("Victor");
vNames.push_back("Nancy");
vNames.push_back("William");
vNames.push_back("Nancy");
sort(vNames.begin(),vNames.end());
vNames.erase(unique(vNames.begin(),vNames.end()),vNames.end());

for(vItr=vNames.begin();vItr!=vNames.end();vItr++)
{
csName=(*vItr);
//TRACE(csName);
//AfxMessageBox(csName);
}

Thursday, September 17, 2009

ExtractIcon of other application

The ExtractIcon function retrieves a handle to an icon from the specified executable file, DLL, or icon file.

HICON hIcon;
hIcon = ExtractIcon( AfxGetApp()->m_hInstance, "C:\\WINDOWS\\system32\\calc.exe", 0 );
SetIcon( hIcon, FALSE );

//You must destroy the icon handle returned by ExtractIcon by calling the DestroyIcon //function.
DestroyIcon(hIcon);

Change or Hide Start button name windows XP



void ChangeOrHideStartButton()
{
HWND hSysTrayWnd = ::FindWindow( "Shell_TrayWnd", 0 );
if( hSysTrayWnd )
{
// Get the start button
HWND hStartBtn = ::FindWindowEx( hSysTrayWnd, 0, "Button", "Start" );
if( hStartBtn )
{
// Hide the start button if shown or show if hidden
if( ::IsWindowVisible( hStartBtn ))
{
::ShowWindow( hStartBtn, SW_HIDE );
}
else
{
::ShowWindow( hStartBtn, SW_SHOW );
//To change name
::SetWindowText(hStartBtn,"Your Name");
}
}

}
}

Monday, September 7, 2009

To Read all section and keys in an Ini File



void ReadSectionsAndKeys(CString csPath)
{
char lpszReturnBuffer[MAX_PATH];
char* pNextSection = NULL;
GetPrivateProfileSectionNames(lpszReturnBuffer,MAX_PATH,csPath);
pNextSection = lpszReturnBuffer;
//TRACE("Section: %s\n", pNextSection);
//printf("Section: %s\n", pNextSection);
// for keys
int nPos=-1;
char lpszKeyNames[8192];
DWORD dSize;
dSize = sizeof(lpszKeyNames);
CString csNameandValue(""), csKey(""),csValue("");
//

while (*pNextSection != 0x00)
{
GetPrivateProfileSection( pNextSection, lpszKeyNames , dSize , csPath );
char *pKeyName = lpszKeyNames;

while (*pKeyName != 0x00)
{
nPos = -1;
if(*pKeyName != 0x00)
{
//TRACE("Keys: %s\n", pKeyName);
csNameandValue = pKeyName;
if((nPos = csNameandValue.Find("=")) > -1)
{
csKey = csNameandValue.Left(nPos);
csValue=csNameandValue.Mid(nPos+1);
}
}
pKeyName = pKeyName + strlen(pKeyName) + 1;
}
pNextSection = pNextSection + strlen(pNextSection) + 1;
if(*pNextSection != 0x00)
{
//TRACE("Section: %s\n", pNextSection);
}
}
}

Friday, August 21, 2009

Get the User App Data Directory



#include <shlobj.h>

char path[_MAX_PATH];

//Get the User App Data Directory
SHGetFolderPath(NULL,CSIDL_LOCAL_APPDATA,NULL,0,path);

//Get the Common App Data Directory
SHGetFolderPath(NULL,CSIDL_COMMON_APPDATA,NULL,0,path);

Tuesday, August 11, 2009

To Close SDI/MDI Application Programmatically

AfxGetMainWnd()->PostMessage(WM_CLOSE);

To lock your machine programmatically

To lock your machine programmatically you can use the API LockWorkStation().

Syntax
C++

BOOL WINAPI LockWorkStation(void);


//Code:
if( !LockWorkStation())
{
// Failed to lock the machine
}

This function has the same result as pressing Ctrl+Alt+Del and clicking Lock Workstation. To unlock the workstation, the user must log in. There is no function you can call to determine whether the workstation is locked.

Monday, July 20, 2009

VC++ code to copy/move records from one database in to another database having the same table.

Download Library and header files from below link:
http://www.codeproject.com/KB/database/CppSQLite.aspx



int CopyMoveDBTable( LPCTSTR lpcSourceDBPath ,LPCTSTR lpcSourceTable , LPCTSTR lpcTargetDBPath ,LPCTSTR lpcTargetTable ,LPCTSTR lpcCriteria ,BOOL bCopy)
{

     CppSQLite3DB* m_db;    
     try
     {
          CString csQuery;              
          m_db=new CppSQLite3DB();         
          m_db->open(lpcSourceDBPath);          
         
          csQuery.Format( "Attach '%s' as sourcedbTable;",lpcTargetDBPath);
          m_db->execDML(csQuery);
          m_db->execDML("begin transaction");
          csQuery.Format( "insert into sourcedbTable.%s select * from main.%s %s ;",lpcSourceTable,lpcTargetTable,lpcCriteria);
          m_db->execDML("commit transaction");
          //insert into sourcedbTable.emptable select * from main.embdb where empid < 1 ;");
          m_db->execDML(csQuery);
          if(bCopy==FALSE)
          {
               m_db->execDML("begin transaction");
               csQuery.Format( "delete from main.%s %s ;",lpcSourceTable,lpcCriteria);
               m_db->execDML(csQuery);
               m_db->execDML("commit transaction");
          }
          csQuery.Format( "DETACH sourcedbTable;");
          m_db->execDML(csQuery);
         
          m_db->close();         
     }

     catch (CppSQLite3Exception& e)
     {
          delete m_db;
         
          AfxMessageBox( e.errorMessage());
          return -1;
     }
     delete m_db;
    
     return 1;

}    

EXample:

     CString csDBPath,csMirrorDB,csTable,csCriteria;
     BOOL bCopy=FALSE;
     csDBPath= "c:\\DatabaseSqlite\\Employee.db";
     csMirrorDB= "c:\\DatabaseSqlite\\Employeemirror.db";
     csTable="EmpTable";
     csCriteria="where empId>5";
     CopyMoveDBTable( csDBPath,csTable, csMirrorDB ,csTable ,csCriteria ,bCopy);

Thursday, July 16, 2009

Code to close Current application

//Code to close Current application

AfxGetMainWnd()->PostMessage(WM_CLOSE);

Program to create shortcut programatically



int createshotcut(CString csShorcutFile,CString csSourceFile,CString csWorkingDirectory,CString Comments )
{
     CoInitialize( NULL );
    
     IShellLink* psl;
    
     // Get a pointer to the IShellLink interface.
    
     HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
         
          IID_IShellLink, (PVOID *) &psl);
    
     if (SUCCEEDED(hres))
         
     {
         
          IPersistFile* ppf;
         
          // Set the path to the shortcut target and add the
         
          // description.
         
          psl->SetPath((LPCSTR) csSourceFile);
         
          psl->SetWorkingDirectory((LPCSTR)csWorkingDirectory);
         
          psl->SetDescription((LPCSTR) Comments );
         
          hres = psl->QueryInterface(IID_IPersistFile, (PVOID *) &ppf);
         
          if (SUCCEEDED(hres))
              
          {
              
               WORD wsz[MAX_PATH];
              
               MultiByteToWideChar(CP_ACP, 0, (LPCSTR) csShorcutFile, -1, wsz, MAX_PATH);
              
               hres = ppf->Save(wsz, TRUE);
              
               ppf->Release();
              
          }
         
          psl->Release();
         
     }
    
     CoUninitialize();

     return 1;
}


Example:
     createshotcut("c:\\mydairy.lnk","d:\\files\\secret.txt","d:\\","My Notepad Shortcut");

Saturday, May 30, 2009

Folder Select Dialog in MFC



BROWSEINFO bi;
ZeroMemory(&bi, sizeof(bi));
TCHAR szDisplayName[MAX_PATH];
szDisplayName[0] = ' ';

bi.hwndOwner = NULL;
bi.pidlRoot = NULL;
bi.pszDisplayName = szDisplayName;
bi.lpszTitle = _T("Please select a folder:");
bi.ulFlags = BIF_RETURNONLYFSDIRS;
bi.lParam = NULL;
bi.iImage = 0;

LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
TCHAR szPathName[MAX_PATH];
if (NULL != pidl)
{
BOOL bRet = SHGetPathFromIDList(pidl,szPathName);
if(bRet)
{
   AfxMessageBox(szPathName);
}

}

Monday, May 25, 2009

Code to Create a file, If file exist already append a GUID with that file and write the content



#pragma comment (lib, "Rpcrt4.lib")

CString GetUniqueGUID( )
{
HRESULT hr = NULL;
CString sUUID(_T(""));
UUID *pUUID = NULL;
BOOL bAllocated = FALSE;
unsigned char *sTemp = NULL;

if (pUUID == NULL)
{
pUUID = new UUID;
bAllocated = TRUE;
}

if (pUUID != NULL)
{
hr = UuidCreate( pUUID );
if (hr == RPC_S_OK)
{
hr = UuidToString(pUUID, &sTemp);
if (hr == RPC_S_OK)
{
sUUID = sTemp;
sUUID.MakeUpper();
RpcStringFree(&sTemp);
}
}
if (bAllocated)
{
delete pUUID;
pUUID = NULL;
}
}
return sUUID;
}


void CreateFileWithoutReplacingExisting(CString & csFileName , CString & csContent )
{

CFileStatus cf;
if(CFile::GetStatus(csFileName,cf)) // File Exist
{
CString csExt ;
CString csGUID=GetUniqueGUID();
csGUID = "_"+csGUID;
int nPos = csFileName.ReverseFind('.');
if(nPos > -1 )
{
csExt = csFileName.Mid(nPos);
csFileName = csFileName.Left(nPos);
csFileName = csFileName+csGUID+"."+csExt;
}
}
CreateFile(csFileName,csContent);

}


int CreateFile(LPCTSTR lpcFileName, LPCTSTR lpcText)
{
if( !lpcFileName || lpcFileName[0]=='\0' )
{
return -1;
}
if(!lpcText || lpcText[0]=='\0') return -1;

CFile cf;
CFileException cfe;

try
{
if(!cf.Open(lpcFileName,CFile::modeCreate|CFile::modeWrite|CFile::shareDenyWrite, &cfe))
{
return 0;
}

cf.Write(lpcText, lstrlen(lpcText) );
cf.Close();
}
catch(CFileException *ce)
{
ce->Delete();
cf.Close();
return -1;
}
return 1;
}

IGlobalInterfaceTable alternate for marshalling in multithreaded enviroment



typedef CComQIPtr<IWebBrowser2,&IID_IWebBrowser2> IWebBrowserQIPtr;
CComPtr<IDispatch> spBrowserPointer ;
IWebBrowserQIPtr pBrowserPtr;
HRESULT hres = S_OK;
DWORD dwCookie = 0;
//Create the GIT
IGlobalInterfaceTable* pGlobalInterfaceTable = NULL;
hres = ::CoCreateInstance(CLSID_StdGlobalInterfaceTable,NULL,CLSCTX_INPROC_SERVER,IID_IGlobalInterfaceTable,(void**)&pGlobalInterfaceTable);
//Register the interface in the GIT
hres = pGlobalInterfaceTable ->RegisterInterfaceInGlobal(pBrowserPtr,IID_IWebBrowser2,&dwCookie);

//this can be used in were ever we unmarshall and use.
//hres =pGlobalInterfaceTable->GetInterfaceFromGlobal(dwCookie,IID_IWebBrowser2,(void**)&pWebBrowserPtr);

//this should be called after using and remove the entry from table
//pGlobalInterfaceTable->RevokeInterfaceFromGlobal(dwCookie);
pGlobalInterfaceTable->Release( );//Don't need the GIT

Friday, May 22, 2009

Download a web page into a file

     HRESULT hr;
     CString csWebsiteName,csFileName;
     csWebsiteName="http://google.com";
     csFileName="c:\\google.htm";
     hr = URLDownloadToFile( NULL ,csWebsiteName ,csFileName , 0 ,NULL );

MFC code to execute a command exe and read the output


CString ReadReturnValueOfCmdFile(CString csExeName, CString csArguments)
{
   CString csExecute;
   csExecute=csExeName + " " + csArguments;
  
   SECURITY_ATTRIBUTES secattr;
   ZeroMemory(&secattr,sizeof(secattr));
   secattr.nLength = sizeof(secattr);
   secattr.bInheritHandle = TRUE;

   HANDLE rPipe, wPipe;

   //Create pipes to write and read data

   CreatePipe(&rPipe,&wPipe,&secattr,0);
   //

   STARTUPINFO sInfo;
   ZeroMemory(&sInfo,sizeof(sInfo));
   PROCESS_INFORMATION pInfo;
   ZeroMemory(&pInfo,sizeof(pInfo));
   sInfo.cb=sizeof(sInfo);
   sInfo.dwFlags=STARTF_USESTDHANDLES;
   sInfo.hStdInput=NULL;
   sInfo.hStdOutput=wPipe;
   sInfo.hStdError=wPipe;
   char command[1024]; strcpy(command,
           csExecute.GetBuffer(csExecute.GetLength()));

   //Create the process here.

   CreateProcess(0, command,0,0,TRUE,
           NORMAL_PRIORITY_CLASS|CREATE_NO_WINDOW,0,0,&sInfo,&pInfo);
   CloseHandle(wPipe);

   //now read the output pipe here.

   char buf[100];
   DWORD reDword;
   CString m_csOutput,csTemp;
   BOOL res;
   do
   {
                   res=::ReadFile(rPipe,buf,100,&reDword,0);
                   csTemp=buf;
                   m_csOutput+=csTemp.Left(reDword);
   }while(res);
   return m_csOutput;
}

Friday, May 15, 2009

UnMashalling WebBroser Pointer

          DWORD dwBrowserPtr = NULL;
          dwBrowserPtr =dwStream //input
         
          ::CoInitialize(NULL);
          IStream** pStream = NULL ;
          pStream = reinterpret_cast<IStream**>(dwBrowserPtr);
         
         
          if( pStream == NULL )
          {
               ::CoUninitialize();
               return -1;
          }
         
          CComPtr<IDispatch> spBrowserPointer ;
          IWebBrowserQIPtr pBrowserPtr;
         
          HRESULT hr = CoGetInterfaceAndReleaseStream(*pStream,IID_IWebBrowser2,(LPVOID*)&pBrowserPtr);
          if ( hr == S_OK )
          {
               //success
          }
          else
          {
               //Failed To get browser pointer
               ASSERT(0);
              
          }

Marshalling WebBrowser Pointer

     /* ============================================================================
     #include <mshtml.h> */


     typedef CComQIPtr<IWebBrowser2,&IID_IWebBrowser2>                              IWebBrowserQIPtr;

     IStream** pStream = NULL ;
     pStream = new IStream* ; // free this memory only at the end of parsing.If you are freeing before that parse will fail

     CComPtr<IDispatch> spBrowserPointer ;         
     spBrowserPointer = APPPTR->m_pdlg->m_webBwsrCntrl.get_Application();

     IWebBrowserQIPtr pBrowserPtr;
     pBrowserPtr = spBrowserPointer;

     HRESULT hr = ::CoMarshalInterThreadInterfaceInStream(IID_IWebBrowser2,pBrowserPtr,pStream);    

     DWORD dwStream = 0;

     if( hr == S_OK )
     {
          dwStream = reinterpret_cast<DWORD>( pStream );
     }
     else
     {
          return -1;
     }

     //(*pStream)->Release(); // Do not release this.While calling CoGetInterfaceAndReleaseStream it will be automaticaly released.

     //=============================================================================

UIThreadImplementation

Create a new class and inherit CWinThread
Add dialog member object in the Thread class


#pragma once
#include "MyDialog.h"
// CMyNewThread

class CMyNewThread : public CWinThread
{
     DECLARE_DYNCREATE(CMyNewThread)

protected:
     CMyNewThread(); // protected constructor used by dynamic creation
     virtual ~CMyNewThread();

public:
     virtual BOOL InitInstance();
     virtual int ExitInstance();

     CMyDialog *m_dlg;

protected:
     DECLARE_MESSAGE_MAP()
};


BOOL CMyNewThread::InitInstance()
{    
     m_dlg = new CMyDialog();
     m_dlg->Create (IDD_DIALOG_MY, NULL);
     m_dlg->ShowWindow( TRUE );
     m_dlg->UpdateWindow();
     return TRUE;

     //return TRUE;
}

// calling the Thread
void CMainFrame::OnNewCreatenewwindow()
{
// TODO: Add your command handler code here
CWinThread *pThread = AfxBeginThread( RUNTIME_CLASS( CMyNewThread ) );
}

Thursday, May 14, 2009

WorkerThread Implementation



class CWorkerThreadImplementationDlg : public CDialog
{
     typedef struct DLG_STRUCT
     {
          CWorkerThreadImplementationDlg* _this;
     }DLG_STRUCT , *PDLGSTRUCT;


void CWorkerThreadImplementationDlg::OnBnClickedOk()
{    
     //CString *cstrValue = new CString("Hai");
     //AfxBeginThread( CWorkerThreadImplementationDlg::RunProgress , (LPVOID)cstrValue );
    
     PDLGSTRUCT lpDLG1 = new DLG_STRUCT;
     lpDLG1->_this = this;
     AfxBeginThread( CWorkerThreadImplementationDlg::RunProgress1 , lpDLG1 );
     PDLGSTRUCT lpDLG2 = new DLG_STRUCT;
     lpDLG2->_this = this;
     AfxBeginThread( CWorkerThreadImplementationDlg::RunProgress2 , lpDLG2 );
}

UINT CWorkerThreadImplementationDlg::RunProgress( LPVOID lpThreadParam )
{
     CString pstr = *((CString*)lpThreadParam);
     return 1;
}

UINT CWorkerThreadImplementationDlg::RunProgress1( LPVOID lpThreadParam )
{
     PDLGSTRUCT pstr = (PDLGSTRUCT)lpThreadParam;
     int nPos = 0;
     while( nPos < 100 )
     {
          pstr->_this->m_Progress1.SetPos( nPos++ );
          Sleep( 100 );
     }
     return 1;
}
UINT CWorkerThreadImplementationDlg::RunProgress2( LPVOID lpThreadParam )
{
     PDLGSTRUCT pstr = (PDLGSTRUCT)lpThreadParam;
     int nPos = 0;
     while( nPos < 100 )
     {
          pstr->_this->m_Progress2.SetPos( nPos++ );
          Sleep( 100 );    
     }
     return 1;
}

Thursday, April 16, 2009

Read and write .ini files



void ReadwriteINI()
{
     CString csIniPath,csKey;
     int nPos;

     char lpszKeyNames[4096];
     DWORD dSize;
     dSize = sizeof(lpszKeyNames);
     csIniPath="settings.ini";
     GetPrivateProfileSection( "IPADDRESS" , lpszKeyNames , dSize , csIniPath );
     char *pKeyName = lpszKeyNames;    
     CString csIP(""), csMyKey(""),csSubnet,csProxyIP,csGateway ,csPort;
    
     while (*pKeyName != 0x00)
     {
          nPos = -1;
          if(*pKeyName != 0x00)
          {
               csKey = pKeyName;
               if((nPos = csKey.Find("=")) > -1)
               {    
                    csMyKey = csKey.Left(nPos);
                    if( csMyKey.Find("IPADDR") > - 1 )
                    {
                         csIP= csKey.Mid(nPos+1);
                    }
                    if( csMyKey.Find("SUBNET") > - 1 )
                    {
                         csSubnet= csKey.Mid(nPos+1);
                    }
                    if( csMyKey.Find("GATEWAY") > - 1 )
                    {
                         csGateway= csKey.Mid(nPos+1);
                    }
                    if( csMyKey.Find("PROXYIP") > - 1 )
                    {
                         csProxyIP= csKey.Mid(nPos+1);
                    }
                    if( csMyKey.Find("PORT") > - 1 )
                    {
                         csPort= csKey.Mid(nPos+1);
                    }
               }
          }
          pKeyName = pKeyName + strlen(pKeyName) + 1;
     }


     if(csIP.IsEmpty())
     {
          csIP="192.168.0.2;
          WritePrivateProfileString("IPADDRESS","IPADDR",csIP,csIniPath);
     }
     if(csSubnet.IsEmpty())
     {
          csSubnet="255.255.255.0";
          WritePrivateProfileString("IPADDRESS","SUBNET ",csSubnet,csIniPath);
     }
     if(csGateway.IsEmpty())
     {
          csGateway="192.168.0.3";
          WritePrivateProfileString("IPADDRESS","GATEWAY",csGateway,csIniPath);
     }
     if(csProxyIP.IsEmpty())
     {
          csProxyIP="198.168.0.1";
          WritePrivateProfileString("IPADDRESS","PROXYIP",csProxyIP,csIniPath);
     }
     if(csPort.IsEmpty())
     {
          csPort="3128";
          WritePrivateProfileString("IPADDRESS","PORT",csPort,csIniPath);
     }

    

}

INI file content:
[IPADDRESS] IPADDR= SUBNET= GATEWAY= PROXYIP= PORT= 


Registry Write example by enable Proxy settings

void EnableProxy()
{
     HKEY hkResult;
     LPCTSTR lpValueName = "VALUE_NAME";
     LPCTSTR lpszKeyName = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
     LPCTSTR lpszValueName = "ProxyEnable";
     // Opens a key in the registry and keeps an handle - hkResult - for future use.
     LONG Res = RegCreateKeyEx (HKEY_CURRENT_USER, lpszKeyName,
          0,NULL,
          REG_OPTION_NON_VOLATILE ,KEY_ALL_ACCESS,NULL, &hkResult,
          NULL);
     if (Res != ERROR_SUCCESS)
          throw "Unable to open the key";

     // Write value in the registry
     DWORD dwData;
     dwData=1;
     Res=RegSetValueEx(hkResult, TEXT(lpszValueName),0, REG_DWORD,(const BYTE*) &dwData, sizeof(DWORD));
     if (Res != ERROR_SUCCESS)
          throw "Unable to set value";


     Res = RegCloseKey(hkResult);    

}

Registry Read example to get Proxy IP and Port settings

void GetProxyIPPortRegistry()
{
     HKEY hkResult;
     LPCTSTR lpValueName = "VALUE_NAME";
     LPCTSTR lpszKeyName = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
     LPCTSTR lpszValueName = "ProxyServer";
     int iValue;

     // Opens a key in the registry and keeps an handle - hkResult - for future use.
     LONG Res = RegCreateKeyEx (HKEY_CURRENT_USER, lpszKeyName,
          0,NULL,
          REG_OPTION_NON_VOLATILE ,KEY_ALL_ACCESS,NULL, &hkResult,
          NULL);
     if (Res != ERROR_SUCCESS)
          throw "Unable to open the key";

    
     CString csIP,csIPAddress,csPort;
     // Reads a value from the registry.
     unsigned long lSize=1;
     DWORD dwType;
     char *lpValue;
     if ((Res = RegQueryValueEx(hkResult,lpszValueName,NULL,NULL,
          NULL,&lSize)) == ERROR_SUCCESS)
     {
          lpValue = new char [lSize + 1];
          Res =
               RegQueryValueEx(hkResult, (LPTSTR)lpszValueName,NULL, &dwType,
               (LPBYTE)lpValue, &lSize);

          if (Res != ERROR_SUCCESS)
               throw "Unable to query value";
          iValue = ::atoi(lpValue);
          csIP=lpValue;
     }
     Res = RegCloseKey(hkResult);

     int nPos=-1;
     if( (nPos=csIP.Find(":"))>-1)
     {
          csIPAddress=csIP.Mid(nPos+1);
          csPort=csIP.Left(nPos);

     }

     delete lpValue;


}

CFileDialog -File open dialog example

CFileDialog fileDlg(TRUE,NULL,NULL,OFN_OVERWRITEPROMPT,"Text & CSV Files (*.txt,*.csv)|*.txt;*.csv|All Files(*.*)|*.*||");
int iRet = fileDlg.DoModal();
CString csFileName;
csFileName = fileDlg.GetPathName();

if(iRet == IDOK)
{
    AfxMessageBox(csFileName);
}
else
{
     AfxMessageBox("No File Selected!");
}

Download Webpage to content to CString

BOOL DownloadURLContent(const char *url, CString &csContent, CString &errorMessage)
{
     const int FILEBUFLEN = 1024;
     char *httpBuff = new char[FILEBUFLEN+1];
     memset( httpBuff ,0 , FILEBUFLEN+1 );
     TCHAR szErr[255];
     errorMessage = "";
     CString csTemp;
    
     TRY {
          CInternetSession session;
          session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 1000);
          session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 3);
          CFile *remoteFile = session.OpenURL(url, 1 ,INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD);
         
          int numBytes;
          while (numBytes = remoteFile->Read(httpBuff, FILEBUFLEN))
          {
               //localFile.Write(httpBuff, numBytes);

               csTemp=httpBuff;
               memset( httpBuff ,0 , FILEBUFLEN+1 );

               csContent=csContent+csTemp;
              
          }
     }
     CATCH_ALL(error) {
          error->GetErrorMessage(szErr,254,NULL);
          errorMessage.Format("%s",szErr);
          return FALSE;
     }
     END_CATCH_ALL;
    
     return TRUE;
}

Thursday, March 26, 2009

CIPAddressCtr converting CString IP address to DWORD

CIPAddressCtr converting CString IP address to DWORD



DWORD GetDWORDIPAddress(CString strIPAddress)
{
     strIPAddress.MakeReverse();// Start from behind

     char DOT = '.';
     DWORD dwReturnValue = 0;

     double dPower = 0.0;

     int length = strIPAddress.GetLength();

     DWORD dwByteTemp = 0;
     int nWhichByte = 0;
     int i = 0;
     for(i; i<length ; i++ ){
          volatile int nTemp = 0;
          char aChar = strIPAddress.GetAt(i);

          if(aChar != DOT){
               int nChar = 0;
               switch(aChar){
                    case '1': nChar = 1; break;
                    case '2': nChar = 2; break;
                    case '3': nChar = 3; break;
                    case '4': nChar = 4; break;
                    case '5': nChar = 5; break;
                    case '6': nChar = 6; break;
                    case '7': nChar = 7; break;
                    case '8': nChar = 8; break;
                    case '9': nChar = 9; break;
                    case '0': nChar = 0; break;
                    default: break;
               }
               nTemp = nChar * (int)pow(10.0 ,dPower);
               dwByteTemp += nTemp;
               dPower++;

               if(i == length-1/*Last Byte*/){
                    dwByteTemp <<= (nWhichByte * 8);//8 Bits = Byte Length
                    dwReturnValue = dwReturnValue | dwByteTemp;
                    dPower = 0;
                    dwByteTemp = 0;
                    nWhichByte++;
               }
          } else {
               dwByteTemp <<= (nWhichByte * 8);// 8 Bits = Byte Length
               dwReturnValue = dwReturnValue | dwByteTemp;
               dPower = 0;
               dwByteTemp = 0;
               nWhichByte++;
          }
     }
     strIPAddress.MakeReverse();//Undo
     return dwReturnValue;
}

Example:

CIPAddressCtrl obj;
DWORD dwIP,dwSubnet,dwGateway,dwProxy;
dwIP=GetDWORDIPAddress(csIP);
dwSubnet=GetDWORDIPAddress(csSubnet);
dwGateway=GetDWORDIPAddress(csGateway);
dwProxy=GetDWORDIPAddress(csProxyIP);

Friday, March 13, 2009

Debugging Tips

While debugging some times we use message box or write in a file.
But we may forget to remove that. To avoid such thing we can use _DEBUG macro to make statements execute only in debug mode not in release mode.

Example:
# ifdef _DEBUG
CStdioFile csTempFile;
if( csTempFile.Open("d:\\temp.txt",CFile::modeCreate|CFile::modeWrite) )
csTempFile.Write(csContents.GetBuffer(csContents.GetLength()+1 ),csContents.GetLength());
csTempFile.Close();
#endif


# ifdef _DEBUG
AfxMessageBox(csContent);
#endif

Saturday, February 28, 2009

How to convert CString into LPTSTR ?

CString csStr = "Hello";
LPTSTR lpStr = csStr.GetBuffer( 0 );
csStr.ReleaseBuffer();

Friday, February 27, 2009

Getting Local Application Path in XP & Vista

typedef HRESULT (WINAPI * SHGetKnownFolderPathFn)(REFKNOWNFOLDERID rfid, DWORD dwFlags, HANDLE hToken,PWSTR *ppszPath);

PWSTR pszPath[1];
SHGetKnownFolderPathFn shGetKnownFolrPth = NULL ;

HINSTANCE hins = LoadLibrary(”Shell32.dll”);

if(hins != NULL)
{

shGetKnownFolrPth = (SHGetKnownFolderPathFn)::GetProcAddress(hins,”SHGetKnownFolderPath”);

if( shGetKnownFolrPth != NULL)
{
shGetKnownFolrPth(FOLDERID_LocalAppDataLow,0,NULL,pszPath);
CString csData=pszPath[0]; // converting from wchar to ANSI.
}
}





int GetCurrentUserLocalLowAppPath(LPTSTR szProfileDir,int dirlen )
{

memset(szProfileDir,0,dirlen);

if(IsWinXP() == TRUE)
{
GetCurrentUserAppPath( szProfileDir, dirlen );
}
else if(IsVista() == TRUE)
{
PWSTR pszPath[1];
SHGetKnownFolderPath(NULL,FOLDERID_LocalAppDataLow,0,NULL,pszPath);
//copying the pszPath to szProfileDir array
}
return 1;

}

Saturday, February 21, 2009

VC++ Code equivalent to DoEvents is Visual basic

//VC++ Code equivalent to DoEvents is Visual basic

void DoEvents()
{
MSG msg;

while ( ::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE ) )
{
if ( ::GetMessage(&msg, NULL, 0, 0))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
else
{
break;
}
}
}

MFC code to get the Path of Appliction and DLL






//MFC code to get the Path of Appliction
CString GetExePath ()
{
   TCHAR szPath[_MAX_PATH];
   szPath[0] = '\0';

   GetModuleFileName( NULL, szPath, sizeof(szPath) );

   CString csPath(szPath);

   int nPos = csPath.ReverseFind('\\');
   if ( nPos != -1)
   {
       csPath = csPath.Left(nPos+1);
   }
   else
   {
       csPath = "";
   }

   return csPath ;

}


//MFC code to get the Path of DLL if it is loaded from different path
#include <atlbase.h>
CString GetDLLPath ()
{
   TCHAR szPath[_MAX_PATH];
   szPath[0] = '\0';

   GetModuleFileName((HINSTANCE)&__ImageBase, szPath, sizeof(szPath) );

   CString csPath(szPath);

   int nPos = csPath.ReverseFind('\\');
   if ( nPos != -1)
   {
       csPath = csPath.Left(nPos+1);
   }
   else
   {
       csPath = "";
   }

   return csPath ;

}

Saturday, February 7, 2009

Useful Cstring Functions



//For replacing nonprintable and non-ASCII unicode to space
CString RemoveNonPrintableCharWithSpacer(LPCSTR lpText)
{
CString csData;
for(;*lpText!='\0'; lpText++)
{
if(*lpText<0 || *lpText>255)
{
csData += " ";
}
else
{
csData += *lpText;
}
}

return csData;
}



//For counting no of small characters
unsigned int CountSmallCharacters(LPCTSTR lpText)
{
unsigned int nSCharCount =0;
for(;*lpText!='\0'; lpText++)
{
if(*lpText>='a' && *lpText <='z')
nSCharCount++;
}
return nSCharCount;
}



//For counting no of characters
unsigned int CountCharacters(LPCTSTR lpText)
{
unsigned int nCharCount =0;
for(;*lpText!='\0'; lpText++)
{
if( (*lpText>='a' && *lpText <='z') || (*lpText>='A' && *lpText <='Z') )
nCharCount++;
}
return nCharCount;
}

Code to Click Internt Explorer Security warning Dialog Box

//Code to Click Internt Explorer Security warning Dialog Box Automatically

BOOL g_bStopDialogWatcherThread = FALSE; // To Stop & start Thread

UINT WindowWatcher(LPVOID lpParam)
{
g_bStopDialogWatcherThread = FALSE;
while(1)
{
Sleep(300);
HWND hWnd;
HWND hWndWarning = ::FindWindow(NULL,"Internet Explorer");
hWnd=::FindWindowEx(hWndWarning , NULL , "Button","&Yes" );
if(hWnd!=NULL && hWndWarning!=NULL)
{
::SetForegroundWindow(hWndWarning);
::SetFocus(hWnd);
::PostMessage ( hWnd , WM_LBUTTONDOWN , 0 , 0 );
::PostMessage ( hWnd , WM_LBUTTONUP , 0 , 0 );
Sleep(1000);
}

if(g_bStopDialogWatcherThread)
{
break;
}
}
return 1;
}

AfxBeginThread(WindowWatcher,THREAD_PRIORITY_NORMAL,0,0,0);//to start the thread

Tuesday, January 27, 2009

How to empty recycle bin programmatically?

While processing or writing huge files to disk, its quite possible that disk will go out of space. To Squeeze and to get more disk space, its a good idea to clean the recycle bin. But how to do it programmatically?


You can use the api - SHEmptyRecycleBin(). See the code snippet below.

SHEmptyRecycleBin( NULL, NULL, SHERB_NOCONFIRMATION | SHERB_NOPROGRESSUI | SHERB_NOSOUND );

Note:
By modifying the options, you can show progress UI, Show confirmation dialog and play sound on finishing task. Just remove the unwanted flags.

Friday, January 23, 2009

Interprocess communication between two application in MFC

This is the example to show how to send a cstring from one application to another.


Paste this follwing code at sender.

CString csData(_T(""));
csData=" This is the message";
COPYDATASTRUCT copyDT;//Is used for Interprocess communication
copyDT.dwData = NULL;
copyDT.cbData = _tcslen(csData) + 1;
copyDT.lpData = ( void* ) ( ( LPCTSTR ) csData );
HWND hWnd = ::FindWindow(NULL,"Receiver application");
// Finding the handle of receiver application and send

// WM_COPYDATA message is used for Interprocess communication
if(hWnd!=NULL)
{
::SendMessage( hWnd, WM_COPYDATA, 0, (LPARAM)&copyDT );
}


At receiver add WM_COPYDATA message.
Paste the following code

CString csReceived;
csReceived=(LPCTSTR)pCopyDataStruct->lpData;

Saturday, January 17, 2009

Function delete a Folder or directory with files and subfolders.

There is no API to delete a directory with files and subfolders.
It is the function to delete folders with files using shell operation.


bool DeleteDirectory(LPCTSTR lpszDir)
{
int len = _tcslen(lpszDir);
TCHAR *pszFrom = new TCHAR[len+2];
_tcscpy(pszFrom, lpszDir);
pszFrom[len] = 0;
pszFrom[len+1] = 0;

SHFILEOPSTRUCT fileop;
fileop.hwnd   = NULL;    // no status display
fileop.wFunc  = FO_DELETE;  // delete operation
fileop.pFrom  = pszFrom;  // source file name as double null terminated string
fileop.pTo    = NULL;    // no destination needed
fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT;  // do not prompt the user


fileop.fAnyOperationsAborted = FALSE;
fileop.lpszProgressTitle     = NULL;
fileop.hNameMappings         = NULL;

int ret = SHFileOperation(&fileop); 
delete [] pszFrom;  
return (ret == 0);
}

This function return true if it succeed.

Friday, January 16, 2009

Debugging in Release mode

Some application work well in debug mode, but crashes in release mode.
Normally we cannot able to debug in release mode.
Following is the settings to debug in release mode.

1) Open project settings by Alt+F7.
2) Select Release configuration.
3) Select “C/C++” tab. Set “Optimizations” as “Disable Debug” and “Debug Info” as “Program Database”.

4) Select “Link” tab. Enable “Generate Debug Info“.
5) Now From menu bar open "Build"--> "Set active configuration", and select Release build as  default.

6) Rebuild the project by F7.
7) Now you can debug in release mode

Thursday, January 1, 2009

How to include library File without using project seettings

include following line in your program

#pragma comment (lib, "yourLibname.lib")

Example:
#pragma comment (lib, "wbemuuid.lib")

Getting all Titles in Internet explorer running instance using COM

#import "mshtml.tlb" // Internet Explorer 5
#include "msHtml.h"
#include "ExDispID.h"
#import "shdocvw.dll"

#include "ExDisp.h"

void CIETabTiltleDlg::OnBnClickedOk() // Copy the following lines
{
SHDocVw::IShellWindowsPtr m_spSHWinds;
m_spSHWinds.CreateInstance(__uuidof(SHDocVw::ShellWindows));
ASSERT(m_spSHWinds != NULL);

CString strCount,m_strWinCount;
long nCount = m_spSHWinds->GetCount();
strCount.Format("%i", nCount);
m_strWinCount = strCount;

IDispatchPtr spDisp;
for (long i = 0; i <>
{
_variant_t va(i, VT_I4);
spDisp = m_spSHWinds->Item(va);
SHDocVw::IWebBrowser2Ptr spBrowser(spDisp);
if (spBrowser != NULL)
{
//m_ctlListLoc is the name of list box of your application

m_ctlListLoc.AddString(spBrowser->GetLocationName());
MSHTML::IHTMLDocument2Ptr spDoc(spBrowser->GetDocument());
if (spDoc != NULL)
{
//m_ctlListTitle is the name of list box of your application
m_ctlListTitle.AddString(spDoc->Gettitle());
}
}
}
m_spSHWinds=NULL;
}

Windows Vista User Account Control article

A nice article about "Windows Vista User Account Control" tips and problems in your programs about Administrators privileges.

Using DLLs and The Windows API in Visual Basic 6.0

Following Link has tutorials about Using DLLs and The Windows API in Visual Basic 6.0

error C2664: 'void ATL::CStringT::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [3]' to 'const wc

If you are getting following error:
error C2664: 'void ATL::CStringT::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [3]' to 'const wchar_t *'

Solution1:
In Project Menu select your Project Properties.

In Configuration Properties
Set "Character Set" as "Use Multi-Byte Character Set"

Solution2:
where ever you are declaring "CString" variable add Unicode support.
Example:
CString csStr(_T("")); //_T("") is for unicode support