Click here to Skip to main content
13,625,272 members
Click here to Skip to main content
Add your own
alternative version

Stats

59.1K views
51 bookmarked
Posted 6 Dec 2004
Licenced

Developers' Tips & Tricks

, 6 Dec 2004
Rate this:
Please Sign up or sign in to vote.
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Naren Neelamegam
Software Developer
United Kingdom United Kingdom
Naren started coding during 1999 with FORTRAN, then COBOL, PASCAL, C, C++, VC++ ..... C#, Java, ASP so on, till today. He claims himself as techie who loves coding, but he is not even sure which technology or platform he loves, most of the time Windows, some time WinCE, some time Linux, nowadays Android and embedded platforms. He can do some query stuffs with Oracle, SQL Server, MySQL. He strongly believes that C/C++ is a must for all programmers, "if you know C/C++, you can do programming on any language". He is an electronic gadget guy who likes to buy small gadgets all the time, at least he will do window shopping on a gadget shop. His interest always have been with Automation in any form, call it a little automated program sitting in his Laptop or a home automation program runs on his mobile. Apart from coding, he likes to do...???

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralVery nice work, thank you. Pin
3x0sk3l3t0n11-Sep-09 1:48
member3x0sk3l3t0n11-Sep-09 1:48 
Generalset focus to thecurrent instance Pin
toxcct25-May-05 20:52
membertoxcct25-May-05 20:52 
GeneralRe: set focus to thecurrent instance Pin
ThatsAlok25-May-05 22:49
memberThatsAlok25-May-05 22:49 
GeneralRe: set focus to thecurrent instance [modified] Pin
Naren Neelamegam9-Jun-05 21:36
memberNaren Neelamegam9-Jun-05 21:36 
Questionmosa&#239;c baground ? Pin
toxcct25-May-05 20:47
membertoxcct25-May-05 20:47 
AnswerRe: mosa&#239;c baground ? Pin
Nareen Neelamegam9-Jun-05 22:06
memberNareen Neelamegam9-Jun-05 22:06 
Hi toxcct,

Your code is correct, but if you want to paint the entire dialog, update your code as follows,
BOOL CMSILauncherDlg::OnEraseBkgnd(CDC* pDC)
{
CBitmap BackGroundBitmap;
BackGroundBitmap.LoadBitmap(IDB_BGND);
CDC MemDC;
MemDC.CreateCompatibleDC(pDC);
MemDC.SelectObject(&BackGroundBitmap);
CRect rect;
GetClientRect(rect);
BITMAP bmp;
BackGroundBitmap.GetBitmap(&bmp);
pDC->StretchBlt(0,0,rect.Width(),rect.Height(),&MemDC,0,0,bmp.bmWidth,bmp.bmHeight,SRCCOPY);
return 1;
}

with regards,
Nareen Neelamegam
GeneralGood Job! Pin
Greg Ellis8-Dec-04 10:05
memberGreg Ellis8-Dec-04 10:05 
GeneralRegisterShellFileTypes() Pin
Neville Franks7-Dec-04 8:51
memberNeville Franks7-Dec-04 8:51 
GeneralRe: RegisterShellFileTypes() Pin
Paul Selormey7-Dec-04 13:03
memberPaul Selormey7-Dec-04 13:03 
GeneralRe: RegisterShellFileTypes() Pin
Neville Franks7-Dec-04 13:45
memberNeville Franks7-Dec-04 13:45 
GeneralLimiting MFC application to one instance Pin
Ravi Bhavnani7-Dec-04 3:36
memberRavi Bhavnani7-Dec-04 3:36 
GeneralRe: Limiting MFC application to one instance Pin
Neville Franks7-Dec-04 9:06
memberNeville Franks7-Dec-04 9:06 
GeneralMoving a captionless dialog Pin
Ravi Bhavnani7-Dec-04 3:31
memberRavi Bhavnani7-Dec-04 3:31 
GeneralNice! Pin
One Stone7-Dec-04 3:21
sussOne Stone7-Dec-04 3:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.180712.1 | Last Updated 7 Dec 2004
Article Copyright 2004 by Naren Neelamegam
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid