Click here to Skip to main content
Click here to Skip to main content

CFormatDriveDialog - A wrapper class for the undocumented SHFormatDrive API function

By , 27 Aug 2002
 

Overview

This class basically brings up the Windows Disk-Format dialog box. You'd have thought it would have become part of the common dialogs by now. What's worse is that some of the information in KB article Q173688 is now incorrect as far as Windows XP and Windows 2000 are concerned. I presume that the KB article was written during the 9x days and they forgot to remove or update it later. What confused me was that the KB article  states that the information in it applies to XP and 2K. The first shock for me was to discover that the Quick-Format option behaved exactly opposite to how it was described in the KB article. In addition the Make-system-disk option was not even working properly. Anyway I've written a class - CFormatDriveDialog that basically wraps the stuff for you. I have stuck to the MS recommended constant definitions where they work, but in other cases I've either discarded them or added my own.

Strong warning

The information in KB article Q173688 is partially incorrect. Do not follow it blindly if you intend to build on this class. Also note that this class should only be used on Win2K/XP systems. The KB article is to be followed for older OS versions like 9x and ME.

Class Reference

There's just one public method here (of course, in addition to the parameter-less constructor).

DoModal

int CFormatDriveDialog::DoModal(HWND hWnd, UINT Drive, bool bQuickFormat, LPCTSTR vol_label);

  • hWnd - The window handle of the dialog's parent. This cannot be NULL.
  • Drive - The drive code (0 for A, 1 for B, 2 for C etc.) I've defined constants like DRIVEA, DRIVEB, DRIVEC etc. which you may use instead of raw numbers. They are defined in the header file.
  • bQuickFormat - If true then the Quick-Format check box is ticked by default.
  • vol_label - The default value for the volume label to be used.

Return Value

IDOK if a successful format was completed and IDCANCEL if the format operation was cancelled or if some error occurred.

Sample Usage

void Cnish_testDlg::OnBnClickedButton1()
{
    UpdateData(true);
    CFormatDriveDialog dlg;
    int d=dlg.DoModal(AfxGetMainWnd()->m_hWnd,DRIVEA,
        bQuickFormat,m_vollab);
    if(d==IDOK)
        MessageBox("yeah"); 
}

Tech Details

We call the SHFormatDrive function from shell32.dll. I use LoadLibrary and load shell32.dll and then call GetProcAddress to get SHFormatDrive's address. I also use SetWindowsHookEx to set a CBT hook because we need to set the volume label. The hook proc calls EnumChildWindows and when we encounter a child window with "Edit" class, we know this is the volume label edit box, because that's the only edit box in the dialog. Refer the source code for full details. A snipped partial listing is given below with comments not found in the actual source code.

int CFormatDriveDialog::DoModal(...)
{

    //...

    // Function pointer to hold SHFormatDrive
    FMTDRIVEFUNC* pshfd;

    // Load the dll
    HMODULE hMod = LoadLibrary("shell32.dll");

    // Chk for error - just in case
    if(hMod)
    {
        // Assign function pointer
        pshfd = reinterpret_cast<FMTDRIVEFUNC*>
            (GetProcAddress(hMod,"SHFormatDrive"));

        // Set a WH_CBT hook
        m_hHook = SetWindowsHookEx(WH_CBT,CBTProc,
            AfxGetApp()->m_hInstance,AfxGetApp()->m_nThreadID);

        // Call the function via the function pointer
        rv = ((*pshfd)(hWnd,Drive,SHFMT_ID_DEFAULT,Options)==
            SHFMT_FMTSUCCESS) ? IDOK : IDCANCEL;

        // Free the dll
        FreeLibrary(hMod);
    }
    
    //...
}

LRESULT CALLBACK CFormatDriveDialog::CBTProc(...)
{
    if (nCode == HCBT_ACTIVATE )
    { 
        // Get handle of Format dialog
        HWND hWnd = reinterpret_cast<HWND>(wParam);

        // Enumerate all child windows to get 
        // volume label the edit box
        EnumChildWindows(hWnd,EnumChildProc,NULL); 

        // Finished our need for the hook
        UnhookWindowsHookEx(m_hHook);
        CFormatDriveDialog::m_hHook = NULL; 
    }
    return FALSE;
}

BOOL CALLBACK CFormatDriveDialog::EnumChildProc(...)
{ 
    char buff[256];
    GetClassName(hwnd,buff,255);

    // The vol label edit box is the only edit control
    if(strcmp(buff,"Edit")==0)
    {
        SetWindowText(hwnd,m_vol_label);
        return FALSE;
    }
    return TRUE;
}

Conclusion

There are several return codes and option codes mentioned in the above mentioned KB article. But none of them work as expected, and some of them don't work at all. In addition the code constant given for Quick-Format works in the exact opposite manner. Of course I base my results from trying out the code on my own machine which is an XP professional box. I also got James T Johnson to test it partially on his XP professional box and Smitha(Tweety) to test it on her Windows 2000 professional box. But I have no idea how this class will work on untested OS versions with or without service packs.

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

About the Author

Nish Sivakumar
United States United States
Member
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralVista problemmemberKranggg22 Oct '09 - 10:25 
doesn't work on Vista! Help!!!
Generala problemmemberqiqi552125 Dec '08 - 15:45 
I test this code .It's very good.
But I found a little problem using it to format harddisk. when formatting the harddisk partition, the progressbar doesn't show percent correcttly?the bigger the disk space , the greater the effect. if the disk space is more than 500MB, the incorrectness of progress percent is very clear .
who can help me?
Generalhimemberqiqi552123 Dec '08 - 17:07 
I test this code .It's very good.
But I found a little problem. when formatting the disk , the progressbar doesn't show percent correcttly?
Generalthe bigger the disk space , the greater the effect.memberqiqi552123 Dec '08 - 19:15 
by the way ,the bigger the disk space , the greater the effect. if the disk space is more than 500MB, the incorrectness of progress percent is very clear .
GeneralUmounting the drivememberjoelparker2 Apr '04 - 6:45 
If I run format twice using this dialog it complains that the drive is busy. Is there a system call to unmount the drive after calling format?
Generalformat disk without dialogmemberpoganka24 Jan '04 - 21:20 
How I can format disk without dialog?
 
thank you
GeneralRe: format disk without dialogmemberzbilal12 Mar '04 - 12:00 
Check this Link
 
http://www.sysinternals.com/ntw2k/source/fmifs.shtml
GeneralRe: format disk without dialog ( How can I do .. )memberka.kevinliu29 Mar '07 - 20:09 
Hi
 
I am trying to write a MFC project(c++) to format a usb drive into FAT or NTFS file system.
But it will display the Dialog window. How can I do to format a usb drive without dialog ?
 
Could someone help me solve this problem ?
Thanks !
 
By the way, the link "http://www.sysinternals.com/ntw2k/source/fmifs.shtml" has been removed.
 
RegardsFrown | :(
 
Kevon
GeneralRe: format disk without dialog ( How can I do .. )memberGeorge Grimes6 Apr '07 - 18:22 
The extension should be "html" not "shtml" so the correct link is
http://www.sysinternals.com/ntw2k/source/fmifs.shtml
 

 
George
GeneralDialogmemberjlechem14 May '03 - 6:05 
This article was extremely helpful! I learned alot and it interfaced with my existing project quite nicely. Thank you so much!! Laugh | :laugh:
 
There are 10 kinds of people in those world. Those who understand binary and those who don't.
GeneralNot a graphic interface and Hi Rating!!! Great!!!memberGabriel 229 Aug '02 - 9:29 
Have you noticed people are usually attracted by nice colored interfaces?
Generally, articles based in beautiful interfaces uses to get the highest ratings.
If you post a source code which solves the problem of universal data compression or encryption, you won't probably get a high rating, unless you include a nice colored and animated progress bar.
Your code doesn't provide a super interface, but received high rating. That's good!!! Smile | :)

GeneralRe: Not a graphic interface and Hi Rating!!! Great!!!editorNishant S29 Aug '02 - 14:03 
Thanks Gabriel 2 Smile | :)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralVery good articlememberMatt Newman29 Aug '02 - 4:05 
Again another great article from Nish.
 
-Suspicious | :suss: Matt Newman / Windows XP ActivistSuspicious | :suss:
-Sonork ID: 100.11179

"You can't seriously believe that you could get away with suing someone over quoting text from a message posted in a public forum, can you?" - John Simmons
GeneralRe: Very good articleeditorNishant S29 Aug '02 - 14:03 
Wow! Thanks Matt Smile | :)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralGood workmemberKannan Kalyanaraman28 Aug '02 - 20:38 
Keep up the good work.
Nish, probably you should write a tutorial for cbt hooks.
I didnt look up CP articles for that one ... Unsure | :~
 
regards
Kannan
GeneralRe: Good workeditorNishant S28 Aug '02 - 20:45 
Thanks Kanna. By the way nice to see your new email address Wink | ;-)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralIt Is DocumentedmemberBlake Coverett28 Aug '02 - 12:27 
Actually, SHFormatDrive and a whole bunch of other miscellaneous bits are newly documented as of yesterday.

 
--
-Blake (com/bcdev/blake)
GeneralRe: It Is DocumentededitorNishant S28 Aug '02 - 12:34 
Blake Coverett wrote:
Actually, SHFormatDrive and a whole bunch of other miscellaneous bits are newly documented as of yesterday.
 
I guess no one will believe me if I said that Bill Gates doesn't like me much Wink | ;-)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: It Is Documented #2editorNishant S28 Aug '02 - 12:38 
Hmmmm
 
I just checked it out on MSDN [online]. They haven't corrected their errors yet! Unless they've changed the values of the constants in the header file. But we don't have access to the header file do we? So we won't know till the next PSDK update.
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

QuestionCan youmemberChris Losinger28 Aug '02 - 6:11 
find a way to make this work over the internet? i'd like to format my brother's HD, as a joke. he lives in NYC. and i want it to run without a taskbar icon, and i don't want it to appear on the process list.
 
oh, and please give me the source.
 
-c
 

A man is like a rusty wheel on a rusty cart,
He sings his song as he rattles along and then he falls apart.
-- Richard Thompson

AnswerRe: Can youmemberJörgen Sigvardsson28 Aug '02 - 7:25 
Bored and pissed off at your brother at the same time? Wink | ;)
 
Preferred storyline:
- I am your father. Search your feelings and you'll know it's the truth. Together we can rule this galaxy like father and son.
- Ok dad. Let's kick some butt!
GeneralRe: Can youmemberChris Losinger28 Aug '02 - 7:38 
Smile | :)
 
nah. my brother's fine.
 
but bored, yeah.
 
-c
 

A man is like a rusty wheel on a rusty cart,
He sings his song as he rattles along and then he falls apart.
-- Richard Thompson

AnswerRe: Can youeditorNishant S28 Aug '02 - 11:51 
Chris Losinger wrote:
find a way to make this work over the internet? i'd like to format my brother's HD, as a joke. he lives in NYC. and i want it to run without a taskbar icon, and i don't want it to appear on the process list.
 
oh, and please give me the source.

 
ROTFLMAO
 
How about - "I want to send this to him as an email attachment, and it should be fetched into his inbox without his knowledge, and should remain as a hidden email, and the program should run without asking him" Wink | ;-)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: Can youmemberChris Losinger28 Aug '02 - 11:49 
yes! thank you! and send the source too!
 
Wink | ;)

 

For men use, if they have an evil turn, to write it in marble:
and whoso doth us a good turn we write it in dust.
-- Sir Thomas More

GeneralRe: Can yousussAnonymous29 Aug '02 - 20:02 
You sound very dubious. I think you aren't telling the truth.
Don't you want this source code to carry out evil act on internet? Are you thinking of writing a virus and pass it on the net? Please, Nishant S don't give this guy the source code, he doesn't sound like a truthful programmer.
GeneralRe: Can youmemberChris Losinger29 Aug '02 - 20:07 
I assure you, that as a Super Hero, i have sworn an oath to only use my powers for Good.
 
-c
 

For men use, if they have an evil turn, to write it in marble:
and whoso doth us a good turn we write it in dust.
-- Sir Thomas More

GeneralRe: Can youeditorNishant S29 Aug '02 - 20:30 
Hmmmm
 
I am sorry dude, but several people have raised objections to my sending you that remote infection source code. The general thinking is that you are one of those wandering virus writers from deep Africa!
 
Nish Wink | ;-)
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: Can youmemberChris Losinger29 Aug '02 - 20:32 
You will pay!!!
 
:b
 
-c
 

For men use, if they have an evil turn, to write it in marble:
and whoso doth us a good turn we write it in dust.
-- Sir Thomas More

GeneralRe: Can youeditorNishant S29 Aug '02 - 20:36 
Chris Losinger wrote:
You will pay!!!
 
ROTFLMAO Laugh | :laugh:
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

GeneralRe: Can youeditorNishant S29 Aug '02 - 20:28 
Anonymous wrote:
he doesn't sound like a truthful programmer
 
Uhmmmm, yeah just what I was thinking too. Looks like one of those virus writers from deep africa to me Suspicious | :suss:
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

AnswerRe: Can youmemberVagif Abilov30 Aug '02 - 3:25 
Yeah, and I can see some other extensions:
 
1. CFormatMultipleDrives. We need to be able to format several drives at once! Preferably using multiple threads.
 
2. CPartionDiskDialog. Enough with FDISK!
 
3. Internet-enabled verion should use Web services. It will be hot! SOAP rules!
 
Poke tongue | ;-P
 
Vagif Abilov
MCP (Visual C++)
Oslo, Norway

 
If you're in a war, instead of throwing a hand grenade at the enemy, throw one of those small pumpkins. Maybe it'll make everyone think how stupid war is, and while they are thinking, you can throw a real grenade at them.
Jack Handey, Deep Thoughts
GeneralNice!memberRavi Bhavnani28 Aug '02 - 2:18 
Another nice one!
 
/ravi
 
Let's put "civil" back in "civilization"
http://www.ravib.com
ravib@ravib.com
GeneralRe: Nice!editorNishant S28 Aug '02 - 11:48 
Ravi Bhavnani wrote:
Another nice one!
 
Thanks Ravi. I like the way you said 'another', as if I have lots of nice ones Wink | ;-) Wink | ;-) Wink | ;-)
 
Nish
 

Author of the romantic comedy

Summer Love and Some more Cricket [New Win]

Review by Shog9
Click here for review[NW]

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 28 Aug 2002
Article Copyright 2002 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid