Search This Blog

Friday, April 12, 2013

How to Paste in MFC Editbox from Clipboard?

When we automating a process, sometime we need to copy some values to clipboard and paste it to a edit box from the clipboard.

In the below example, I created a edit box with the name m_edEditbox, then I am setting focus to that edit box.

Normally we use ctrl+v as the shortcut to paste in windows.

I am generating the ctrl+v keyboard event programatically using the following code.
 
 

    m_edEditBox.SetFocus();
    Sleep(100);
    keybd_event( VK_CONTROL, MapVirtualKey( VK_CONTROL, 0 ), 0, 0 );
    Sleep(100);
    keybd_event( 'V', MapVirtualKey( 'V', 0 ),  0, 0 );
    Sleep(100);
    keybd_event( 'V', MapVirtualKey( 'V', 0 ), KEYEVENTF_KEYUP, 0 );
    Sleep(100);
    keybd_event( VK_CONTROL, MapVirtualKey( VK_CONTROL, 0 ), KEYEVENTF_KEYUP, 0 );
    Sleep(100);

Extract All Digits From A String

Sometimes we may need to extract only digits from a string.

For example,
When we display a phone number we display as 001-00-100-200, some thing like that.
but when we save this number is a database as integer, then we need to remove hyphen and other characters.

In such situation we can use this following function.
 
 

CString GetAllDigits(LPCSTR lpTxt)
{
    CString csDigits;
    for(;*lpTxt!='\0'; lpTxt++)
    {
        if(*lpTxt>=48 && *lpTxt <58)
        {
            csDigits += *lpTxt;
        }
    }
    return csDigits;
}

Count Digits, Alphabets, Special Characters and Total number of characters

Some software have option to find the number of digits, alphabets, special characters and total number of  characters.

This type of functions are helpful is parsing texts. This function uses the ASCII values of each characters and gives the count.  Zip code in Canada has alphabets and numbers for such type of validation, we can use this function.

This function accept a string as pointer to a character and  give the count as reference.



unsigned int CountLetters(LPCTSTR lpTxt, unsigned int &nAlphabetCount, unsigned int &nDigitCount, unsigned int &niSpecialCharCount)
{
    unsigned int nLength =0; 
    nAlphabetCount = 0;
    nDigitCount = 0;
    niSpecialCharCount =0;

    for(;*lpTxt!='\0'; lpTxt++)
    {
        if( (*lpTxt>='a'  && *lpTxt <='z') || (*lpTxt>='A'  && *lpTxt <='Z'))
        {
            nAlphabetCount++;
        }
        else if(*lpTxt>=48 && *lpTxt <58)
        {
            nDigitCount++;
        }
        else if( *lpTxt < 127 && *lpTxt>32 && *lpTxt != 160)
        {
            niSpecialCharCount++;
        }
        nLength++;
    }
    return nLength;
}

Counting Number Of Digits In C++

We validate phone numbers, Zip code, credit card numbers, etc using number of digits.

How to get the number of digits?

 When we have a number as the  string  then we can find the count by using the ASCII value.
ASCII value of '0' is 48 and '9' is 57. we have to check the ASCII of each character and if it matches the numerical range then we have increase the count.

Following function helps us to count the number of digits



unsigned int CountDigits(LPCTSTR lpTxt)
{
    unsigned int nCount =0;
    for(;*lpTxt!='\0'; lpTxt++)
    {
        if(*lpTxt>=48 && *lpTxt <58)
            nCount++;
    }
    return nCount;
}

Deleting A Directory in C++

When we delete a directory programatically we can't delete it when there is some files or folders inside the directory.  We can delete only the empty folders.

Otherwise, We usually delete  recursively search and delete all files and then we delete all folders and finally we delete the folder which we want to delete.

But the following code snippet uses shell operation and delete the directory directly without any recursive function.

It is faster than the recursive function.

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

Friday, April 5, 2013

C# Utility Class To Create and Access MS Excel

This class can be used to create a Excel workbook and setting values in a particular cell.

Many times we need to save some values in excel and do some calculations programatically.
We usually automate  performance calculation and calculating percentage of improvement using the following class.

This class helps us to save your time in excel automation and performance calculation.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

class CExcelHelper
{
    public int m_nCol;
    public int m_nRow;
    private Excel.Application m_oXL;
    private Excel._Workbook m_oWB;
    private Excel._Worksheet m_oSheet;
    private Excel.Range m_oRng;
    public void createExcel()
    {
        try
        {
            //Start Excel and get Application object.
            m_oXL = new Excel.Application();
            m_oXL.Visible = true;


            //Get a new workbook.
            m_oWB = (Excel._Workbook)(m_oXL.Workbooks.Add(Missing.Value));
            m_oSheet = (Excel._Worksheet)m_oWB.ActiveSheet;

            m_oXL.Visible = true;
            m_oXL.UserControl = true;
        }
        catch (Exception theException)
        {
            ErrMsg(ref theException);
        }
    }
    public bool SetValue(int nRow, int nCol, ref string strValue)
    {
        //Row and col should from 1S
        if (nRow < 1 || nCol < 1)
            return false;


        bool bRet = true;

        try
        {
            m_oSheet.Cells[nRow, nCol] = strValue;
        }
        catch (Exception e)
        {
            ErrMsg(ref e);
            return false;
        }
        return bRet;
    }

    public void CloseExcel()
    {
        m_oXL.Quit();
    }
    private void ErrMsg(ref Exception theException)
    {
        String errorMessage;
        errorMessage = "Error: ";
        errorMessage = String.Concat(errorMessage, theException.Message);
        errorMessage = String.Concat(errorMessage, " Line: ");
        errorMessage = String.Concat(errorMessage, theException.Source);
        MessageBox.Show(errorMessage, "Error");
    }
    public bool ApplyFormula(String strRangeStart, String strRangeEnd, string strFormula)
    {
        bool bRet = true;

        try
        {
            m_oRng = m_oSheet.get_Range(strRangeStart, strRangeEnd);
            m_oRng.Formula = strFormula;
        }
        catch (Exception e)
        {
            ErrMsg(ref e);
            return false;
        }
        return bRet;
    }
    private string RangeAddress(Excel.Range rng)
    {
        return rng.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1);
    }
    public string CellAddress(int row, int col)
    {
        return RangeAddress(m_oSheet.Cells[row, col]);
    }
}
 
 
 
Usage:
//Excel Open
CExcelHelper objExcel = new CExcelHelper();
 objExcel.createExcel();
  string str="Sample";
 objExcel.SetValue(2, 1, ref str);

C# Code To Split String By Using Tabs As Delimmiter

We save some files as Tab delimited. In MS-Excel also have option to save the file as Tab delimited file. In that file there is a tab between each cells. We can read cell by cell using the following sample code.

Following Code snippet will split string using tab and store it in to a ArrayList.

public static void SplitTabs(string strText, ArrayList ArrTabs)
{

    int nStart = 0;
    int nPos = -1;
    int nLength = 0;
 //   strText = strText.Trim();
    nPos = strText.IndexOf("\t");
    if (nPos == -1 && strText.Length > 0)
    {
        ArrTabs.Add(strText);
    }
    while (nPos > -1)
    {
        nLength = nPos - nStart;
        string strLine = strText.Substring(nStart, nLength);
        strLine = strLine.Trim();

    //    if (strLine.Length > 0)
        {
            ArrTabs.Add(strLine);
        }
        nStart = nPos;
        nPos = strText.IndexOf("\t", nPos + 1);
        if (nPos == -1 && strText.Length > (nStart + 1)) //Last and remaining Text
        {
            strLine=strText.Substring(nStart );
            strLine = strLine.Trim();
            if (strLine.Length > 0)
            {
                ArrTabs.Add(strLine);
            }
        }
        nStart ++;

    }
}
Usage:
string strTxt = "'abc'\t'bcd'\t'xyz'";
ArrayList ArrLines= new ArrayList();
SplitTabs(strTxt, ArrLines);
 foreach (string str in ArrLines)
 {
      Console.WriteLine(str);
 }

Output: