Search This Blog

Showing posts with label MFC. Show all posts
Showing posts with label MFC. Show all posts

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

}

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");

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;
}

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.

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;
}

Friday, May 22, 2009

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;
}

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= 


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!");
}

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

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;