65.9K
CodeProject is changing. Read more.
Home

Developers' Tips & Tricks

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.25/5 (49 votes)

Dec 7, 2004

1 min read

viewsIcon

69439

Some useful tips and tricks for developers.

Introduction

The following are some tricks and tips that I have explored across my projects. Just I want to share it with you all. May be you are all well known about something or all things in this article. But, just I am looking for beginners to take advantage of this article.

Drag & Drop option for your application

  • Add WS_EX_ACCEPTFILES style to your application’s extended styles.
  • Add WM_DROPFILES message handler to your application.
void CYourDialog::OnDropFiles(HDROP hDropInfo) 
{
    CString sFile;
    char *s=sFile.GetBufferSetLength(255);
    // Get number of files
    int numFiles=DragQueryFile(hDropInfo,0xFFFFFFFF,s,255); 
    sFile.ReleaseBuffer(); 
    for(int i=0;i<numFiles;i++)
    {
        s=sFile.GetBufferSetLength(255);
        DragQueryFile(hDropInfo,i,s,255);  // Get filename using the index
        sFile.ReleaseBuffer();
        MessageBox(sFile);
    }    
CDialog::OnDropFiles(hDropInfo);
}

Limiting MFC application to one instance

Put the following code in OnInitInstance().

BOOL bFound=FALSE;
HANDLE hMutexOneInstance =  CreateMutex(NULL,TRUE,_T("UniqueInstanceName"));
if(GetLastError() == ERROR_ALREADY_EXISTS)
       bFound = TRUE;
if(hMutexOneInstance) 
    ReleaseMutex(hMutexOneInstance);
if(bFound) return FALSE;

Getting the IP Address

Include the Winsock header file.

#include <WinSock.h>

Include the wsock32 library.

#pragma comment(lib,"wsock32.lib")
BOOL CFun::GetIPAddress(CString &IPAddress)
{
  WORD wversion;
  WSADATA wsData;
  char name[255];
  PHOSTENT hostinfo;
  wversion=MAKEWORD(1,1);
  char *ip;
  if(WSAStartup(wversion,&wsData)==0)
  {
    if(gethostname(name,sizeof(name))==0)
    {
      if((hostinfo=gethostbyname(name))!=NULL)
      {
         int count=0;
         while(hostinfo->h_addr_list[count])
         {
           ip=inet_ntoa(*(struct in_addr*)hostinfo->h_addr_list[count]);
           CString st;st.Format("%s",ip);
           IPAddress+=st;
           ++count;
         }
       }
       else return FALSE;
     }
     else return FALSE;
   }
   else return FALSE;
   return TRUE;
 }

Moving a Captionless dialog

void CYourDialog::OnLButtonDown(UINT nFlags, CPoint point)
{
    CDialog::OnLButtonDown(nFlags,point);
    PostMessage(WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(point.x,point.y));
}

Creating a Hollow brush

CBrush *br=CBrush::FromHandle((HBRUSH)GetStockObject(HOLLOW_BRUSH));

Reading Bitmap from a file

HBITMAP hbitmap=(HBITMAP) ::LoadImage( AfxGetApp()->m_hInstance, 
                                       ”c:\\test.bmp”, 
                                       IMAGE_BITMAP, 
                                       LR_DEFAULTSIZE, 
                                       LR_DEFAULTSIZE, 
                                       LR_LOADFROMFILE);

Painting background with an image

BOOL CYourDialog::OnEraseBkgnd(CDC* pDC)
{
    CBitmap mybitmap;
    mybitmap.LoadBitmap(IDB_BITMAP1);
    CDC mymemdc; 
    mymemdc.CreateCompatibleDC(pDC);
    mymemdc.SelectObject(&mybitmap);
    PDC->BitBlt(0,0,100,100,&mymemdc,0,0,SRCCOPY);
    return 1;
}

Sending message to all windows

::SendMessage(HWND_BROADCAST,WM_CLOSE,0,0);

Registering an extension for your application

The following function can be used with any type of VC applications (Dialog based, SDI, MDI....). The core is, the following code will register its application directly to the Registry. Doc/View Architecture has its own way to register its document's extension (CWinApp::RegisterShellFileTypes(BOOL bCompat=FALSE)).

BOOL RegisterExtension(CString sExt, CString sDescription)
{
    // sDescription is the description key for you application
    sDescription.Replace(" ","");            
    sExt.Replace(" ","");                // sExt – extension to register
    if(sExt.IsEmpty()) return FALSE;
    if(sDescription.IsEmpty()) return FALSE;

    sExt.Replace(".","");
    sExt="."+sExt;

    CString str=GetCommandLine(); // Getting the application name
    CString app;
    int index=str.Find(":",0);
    index=str.Find(":",index+1);
    if(index==-1) app=str;
    else app=str.Mid(0,index-1);

    app.Replace("\"",""); 
    app+=" \"%1\"";
    HKEY hkey;
    RegOpenKeyEx(HKEY_CLASSES_ROOT,"",0,KEY_QUERY_VALUE,&hkey);
    DWORD dw;
    RegCreateKeyEx(hkey, sExt.operator LPCTSTR() , 0L, NULL,
            REG_OPTION_NON_VOLATILE, 
            KEY_ALL_ACCESS, 
            NULL,&hkey, &dw );
    CString key=sDescription;
    RegSetValueEx(hkey,"",0,REG_SZ,(BYTE *)key.operator LPCTSTR(),
               key.GetLength());
    RegCloseKey(hkey);

    RegOpenKeyEx(HKEY_CLASSES_ROOT,"",0,KEY_QUERY_VALUE,&hkey);
    RegCreateKeyEx (hkey, key, 0L, NULL,
            REG_OPTION_NON_VOLATILE, 
            KEY_ALL_ACCESS, 
            NULL, &hkey, &dw);
    RegCreateKeyEx (hkey, "shell",  0L, NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_ALL_ACCESS, 
            NULL,&hkey,  &dw);
    RegCreateKeyEx (hkey, "open", 0L, NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_ALL_ACCESS, 
            NULL,&hkey, &dw);
    RegCreateKeyEx (hkey, "command", 0L, NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_ALL_ACCESS, 
            NULL,&hkey, &dw);
    RegSetValueEx(hkey,"",0,REG_SZ, (LPBYTE)(LPCTSTR)app,app.GetLength());
    RegCloseKey(hkey);

    RegOpenKeyEx(HKEY_CLASSES_ROOT,key,0,KEY_QUERY_VALUE,&hkey);
    RegCreateKeyEx (hkey, "DefaultIcon", 0L, NULL,
            REG_OPTION_NON_VOLATILE, 
            KEY_ALL_ACCESS,
            NULL,&hkey, &dw);
    app.Replace(" \"%1\"",",0");
    RegSetValueEx(hkey,"",0,REG_SZ, (LPBYTE)(LPCTSTR)app,app.GetLength());
    RegCloseKey(hkey);
    return TRUE;
}

Getting screen resolution

void GetScreenResolution(int &xValue, int &yValue)
{
    xValue = GetSystemMetrics ( SM_CXSCREEN ) ;
    yValue = GetSystemMetrics ( SM_CYSCREEN ) ;
}

Getting path of executable for a file

char buff [MAX_PATH] ;
FindExecutable ( "C:\\myhtml.htm", NULL, buff ) ;

Changing color of a progress bar control

CProgressCtrl::SendMessage ( PBM_SETBARCOLOR, 0, RGB ( 255, 0, 0 ) ) ;

Setting a system wide cursor

Define OEMRESOURCE in stdafx.h.

#define OEMRESOURCE
HCURSOR hcur1 = AfxGetApp()->LoadCursor(IDC_YOURCURSOR);
HCURSOR hcur2 = CopyCursor(hcur1);
SetSystemCursor(hcur2,OCR_NORMAL);

Getting directory list in your combobox

m_combo.Dir ( DDL_DIRECTORY, "C:\\Windows\\*.*" )  ; 
m_combo.SetCurSel ( 1 ) ;

Parsing your commandline information

CCommandLineInfo cmdInfo;
AfxGetApp()->ParseCommandLine(cmdInfo);
MessageBox(cmdInfo.m_strFileName)    // Your command line input filename

to be continued...

Dear Friends

I didn't describe any of the codes above. I have not enough time to spend for that. Just I have presented the code.

None of the articles can satisfy one's expectations. But, each article should be a seed for your technical growth. Thus, I believe that this would be a seed. Thank you all.