Windows Code Examples
A quick cheat sheet for C++/Windows API programming. I'm doing a little updating and improving since it's getting a lot of hits. Please put any requests for additional information in the voting comment box below so I can keep improving it.
by Mark Henri

adding libraries from source code
borland w32 help
casting
close not allowed
critical sections
CPU Speed
directory listing
disenchanted with mfc
events
execute and wait
file exists
get instance
get local ip address
global string substitution
Messages-First and Last
mouse hit in task notification area
money class
maximized on startup
mutexes
obtaining a uuid
path of the executable
semaphores
sleeping threads
special characters
tear off menu
testing autorun.inf
thread example 2
thread example 1
tool tips
version string
WinSock programming URLs
Setting System Time
This page is getting a lot of hits; consequently, I need your feedback to make it better. Please, help me improve this resource with your rating and comments. Thanks.

Adding Libraries From Source Code
Add librarys automatically from source code...
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "comctl32.lib")

Borland w32 help

Borland W32 Help File Zipped

Casting

   HWND h; int n; long ptr;
   h = reinterpret_cast<HWND>(ptr); // safer than explicit cast
   n = reinterpret_cast<HWND>(ptr); // compiler will complain

   
   static_cast
   dynamic_cast
   const_cast


Close Not Allowed
Simon L wrote:
> 
> I want to make a prog imposible to close. The user see a window, but
> can't be closed and if the prog receive PostQuitMessage it will ignore
> it and continu.
> 
> This is for a security prog.

Normally it is the responsibility of the program itself to close--or not
to close--when requested. The request can come in a variety of forms:
WM_SYSCOMMAND message with SC_CLOSE when the close button on a window is
clicked or the "Close" menu item is selected from the system menu;
WM_CLOSE message which may come from the task manager, etc. Your program
can choose to ignore these messages if you wish.

PostQuitMessage() _never_ comes from outside your program. If you look
at its parameters, you will see that there is no way to direct the
resulting WM_QUIT message to any program other than the one calling the
function.

Note, however, that any program can be closed by calling
TerminateProcess(); this is what TaskManager does if your program does
not shut down after TaskManager sends it a WM_CLOSE message.

Norm

Critical Sections
EnterCriticalSection() will put the thread to sleep if the critical section object is in use elseware. If multiple threads are awaiting release, only one will arbitrarily gain it.
   CRITICAL_SECTION cs;
   InitializeCriticalSection( &cs );
   ...
   // somewhere later in the code where
   // you're managing shared object...
   EnterCriticalSection( &cs );
   LeaveCriticalSection( &cs );
   ...
   DeleteCriticalSection( &cs );
The above code is prone to errors and is a poor resource management strategy. If you are using C++, check out this set of class wrappers designed by Bartosz Milewski for managing critical section locking--
   // somewhere with the resource to protect
   CCriticalSection critSect;

   // later in the code...
   {
      CLock lock( critSect );
      // perform action which may throw
      sharedMemoryObject.Update(...);
      // guaranteed automatic release of lock
      // when CLock object goes out of scope
   }
By decoupling the critical section object with it's lock manager, an extremely safe implementation it is created. There is absolutely no way to leave this critical section in a locked state. Check out the source code and other useful classes.

Directory Listing

   WIN32_FIND_DATA sfd;
   HANDLE h = FindFirstFile( "c:\\My Documents\\*.*", &sfd );
   if ( h != INVALID_HANDLE_VALUE )
   {
      do
      {
         // do something with the file name sfd.cFileName...
      }
      while ( FindNextFile( h, &sfd ) );
   }


Disenchanted with MFC
"James A. Donald" <jamesd@echeque.com>
I, and all programmers at the company where I work, have come to the conclusion that MFC is a cancer that has escaped from the comprehension and control of those who originally created it, and that writing any large project in MFC will lead to the project failing.
Most of us, in a somewhat ad hoc manner, have created applications with lots of gui, without using MFC, but of course, we have no standard framework, and not much example code.
I am looking for a body of books, examples, and source code, an alternative framework.
In Visual basic 5.0 there are a bunch of controls that one can glue together, to make whatever user interface one desires. I would like to do this in Win32, but do not really know how to do it, outside the MFC framework. The trick that most of us have used is to create containers for the IE control, and then do the user interface in HTML, which is more or less the trick that Microsoft used to write outlook, however each of us has done this in ways that are utterly different from each other, almost incomprehensibly different, and none of us have documented or explained what we did. Each of us was pioneering, and I suspect that many of the routes we wound up walking was strange and complex.
I would like to be able to take the usual gadgets, menus, toolbars, splitter bars, and all the things one finds in a dialog box, and use them directly from C++. All this is sort of documented in bits and pieces, here and there, but it seems to me that in abandoning MFC, we have wound up reinventing the wheel a lot, and producing some mighty strange wheels.
I am really looking for a book or collection of web pages and source code along the lines of "Here is how to do gui code without using that stupid MFC shit"

James A. Donald



See my article on this subject. Then check out the Windows Class library Code on my vanityware code page. There's an example project there too showing some of the possibilities with an MDI application. -Mark Henri

Events
The most primitive, they are used to signal that an operation is completed.

   // a2=manual reset required, a3=signaled (won't block)
   HANDLE h = CreateEvent(NULL, TRUE, FALSE, "myEventName" );

   // makes the WaitForSingleObject or WaitForMultipleObject calls block
   ResetEvent( h );

   // releases waiting threads
   SetEvent( h );

   // releases waiting threads and resets
   PulseEvent( h );

   // blocks when ResetEvent() has been called.
   WaitForSingleObject( h, INFINTE );


File Exists
I've been doing this--
#include <windows.h>

BOOL FileExists( const char* fileName )
{
   WIN32_FIND_DATA d;
   HANDLE fh = FindFirstFile( fileName, &d );
   if ( fh == INVALID_HANDLE_VALUE )
   {
      return FALSE;
   }
   FindClose( fh );
   return TRUE;
}
but this is a great tip from Stephen Kellet--
if (GetFileAttributes(fullPathNameToFile) != -1)
{
   // file or directory with this name exists
}


Get Instance
To get the instance of the currently executing code, use--
   GetModuleHandle(NULL);



Get Local IP Address
This get the IP addresses for the machine it's run on. WinSock must initialized before using; insert this class in the main program thread. Also be sure to link in ws2_32.lib.
GetLocalAddress.h
GetLocalAddress.cpp


Global String Substitution
Here's the basis of a replace using the standard library; however, I've already got them defined as functions in these source code files-- StringStuff.h and StringStuff.cpp.
   string s = "2, 1, 0, 15";
   cout << "s=" << s.c_str() << endl;
   {
      string substr1 = ", ";
      string substr2 = ".";
      for ( int p=s.find( substr1.c_str() ); p != s.npos; p=s.find( substr1.c_str(), p ) )
      {
         s.replace( p, substr1.length(), substr2 );
         p += substr2.length();
      }
   }
   cout << "s=" << s.c_str() << endl;

At first glance, this code may appear to be inefficient. However, I received some advice from another programmer one time to always run your application through a profiler before starting to economise anything. You'll be amazed at where the bottlenecks are and they're never where you expect.

Mouse Hit in Task Notification Area
So you're putting a little icon down in the task notification area (aka "the tray") but when the message arrives, you noticed that the mouse coordinates are nowhere to be found?  I turns out that they aren't included with the event message (strange huh?).  There is a way to get it and it's simple.  Simply use GetCursorPos() immediately upon receiving the notification. You can combine with with TrackPopupMenu to put the menu in the correct position. You'll notice by right clicking everyone else's tna icon while quickly dragging the mouse that the menus appear in the middle of the screen thereby proving that's the way everyone else is doing it also.

Money Class
> Does anyone know of a C++ based big integer library available?
> 
> I am writing a financial application that needs to calculate huge numbers
> accurately.

My preference at the present time is the Windows port of NTL, though 
I've also used MIRACL, which also works well.  They're both easier to 
use in C++ than in C.

Maximized On Startup
Hi CC,

> I'm trying to create a window that is initially maximized. I'm
> specifying a window style of WS_OVERLAPPED|WS_MAXIMIZE. The problem is
> that I can't figure out what to set the x, y, width, and height params
> to in CreateWindow(). If I set them to CW_USEDEFAULT, then that seems
> to override the WS_MAXIMIZE setting. If I set them, to 0, or -1, I get
> a teeny tiny window.

Use the SW_MAXIMIZE parameter along with CW_USEDEFAULT as in:

   hWnd = CreateWindow( szAppName,"Title",
                        WS_OVERLAPPEDWINDOW | WS_MAXIMIZE,
                        CW_USEDEFAULT,SW_MAXIMIZE,
                        CW_USEDEFAULT,SW_MAXIMIZE,
                        NULL,NULL,hInstance,NULL);

Tom

Mutexes
Only one thread at a time can own a mutex until ReleaseMutex() is called.
   // 2=manual reset required, 3=signaled (go)
   HANDLE g_mutex = CreateMutex(NULL, TRUE, FALSE, "myMutexName" );

   // releases ownership of mutex object
   ReleaseMutex( g_mutex );

   // blocks. Sets mutex to non-signaled (busy). Call Release() when done.
   WaitForSingleObject( g_mutex, INFINTE );


Obtaining a UUID

   // set GUID
   string s;
   UUID u;
   RPC_STATUS stat = UuidCreate( &u );
   if ( stat == RPC_S_OK )
   {
      unsigned char* p;
      stat = UuidToString( &u, &p );
      if ( stat == RPC_S_OK )
      {
         s.assign( (char*)p );
         stat = RpcStringFree( &p );
         // if ( stat == RPC_S_OK )
         // else
      }
   }


Path of the Executable
Here's the code that shows how it works but you can just use these predefined functions instead--

GetExePath.h
GetExePath.cpp

There's other useful functions in there also that will save you time coding.
   char ach[512];
   ::GetModuleFileName( NULL, ach, sizeof( ach ) );
   ach[sizeof(ach)-1] = '\0'; // insurance
   string sExePath = ach;


Semaphores
Used for resource counting tasks. Similar to InterlockedIncrement() except that the Wait function blocks if the count is over the limit.

   // 2=min count, 3=max count
   HANDLE h = CreateSemaphore(NULL, 0, 10, "mySemaphoreName" );

   // increments count by one (can't increment more than one).
   WaitForSingleObject( h, INFINTE );

   // releases by value of 2nd argument
   ReleaseSemaphore( h, 1, NULL );


Sleeping Threads
cisco wrote:
> 
> I'm tryin to do a little simple thread practice program. What i basically
> want to do it call a thread where i use Sleep() for a specified amount of
> time but i would like to kill that thread before the Sleep() finishes it if
> i want to...
> 
> Now i'm reallly new to threads and windows programming in general so i may
> be missing something obvious. This is a console application and i'm just
> pretty much trying to mess with threads right now.
> 
> When i use CloseHandle() instead of ExitThread() it works the way i want it
> to.. but it looks like i'm not doing it "right"... Maybe i should do some
> more windows programming first but i want to get this right first ;) -- i
> wsa using _beginthread() before but i couldn't find a write terminate
> function to that one... --?
> 
> any help would be very much appreciated!
> 
> -------------------- danger.. flawed code below -------------
> 
> #include <windows.h>
> #include <process.h>
> #include <iostream>
> 
> using std::cout;
> using std::cin;
> using std::endl;
> 
> DWORD threadId;
> HANDLE hThread;
> 
> DWORD WINAPI Thread2(PVOID pparam) 
> {
>     Sleep(5000);
>     cout << "It did it\a";
>     cout.flush();
>     return 0;
> }
> 
> int main(void) {
>     hThread = CreateThread(NULL, 0, Thread2, NULL, 0, &threadId);
>     if(hThread == NULL)
>         file://error
> 
>     int termThread;
>     LPDWORD status;
> 
>     cout << "Enter 10 to terminate thread: ";
>     cin >> termThread;
> 
>     if(termThread == 10) {
>         ExitThread(GetExitCode(hThread, status));
>         file://CloseHandle(hThread);
>         cout << "There should be no beep..." << endl;
>     }
> 
>     return 0;
> 
> }
ExitThread causes the thread that calls it to exit, so you are exiting from your main thread instead of killing thread2.

There is no good way to kill a thread without the thread's cooperation. You should always arrange a way to tell a thread to exit, then have the thread perform its own cleanup and exit. One way to do that in your test case is to use WaitForSingleObject(hKill, 5000) instead of Sleep(5000). The main thread must call CreateEvent to initialize hKill before starting the thread. Then the main thread can SetEvent(hKill) to signal the thread to exit. That will cause WaitForSingleObject to return early with WAIT_OBJECT_0 and the thread can exit.

--
Scott McPhillips [VC++ MVP]


Special Characters
¾

Tear Off Menu
Add a button to the dialog with a label like 'More...' on it. Put this code in it's event handler--
   RECT rt;
   ::GetWindowRect( m_lbPolicies.GetSafeHwnd(), &rt );
   int x = rt.left + ((rt.right - rt.left) / 4);
   int y = rt.top + ((rt.bottom - rt.top) / 2);
   HMENU hmenu = ::LoadMenu( AfxGetInstance(), MAKEINTRESOURCE( IDR_POLICY_TEAROFF ) );
   if ( hmenu )
   {
      HMENU hsubmenu = ::GetSubMenu( hmenu, 0 );
      if ( hsubmenu )
         ::TrackPopupMenu(  hsubmenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, 
            x, y, 0, GetSafeHwnd(), NULL );
      DestroyMenu( hmenu ); // recursive; does the submenu also
   }

Thread Example 1
void threadfunction(void * p) {
   _endthread();
}

void main( void ) {
   _createthread( threadfuncptr, 0, NULL ); // 2=stacksize, 3=argptr
   getch();
}


Thread Example 2
int g_nIndex = 0;
const int MAX_TIMES = 1000;
DWORD g_dwTime[MAX_TIMES];
CRITICAL_SECTION g_CriticalSection;

int WINAPI WinMain( void ) {
   HANDLE hThreads[2];

   // Initialize the critical section before the threads so
   // that it is ready when the threads execute.
   InitializeCriticalsection( &g_CriticalSection );

   hThreads[0] = CreateThread( ..., FirstThread, ...);
   hThreads[1] = CreateThread( ..., SecondThread, ...);

   // Wait for both threads to terminate.
   // Don't worry about this lin; it will be explained shortly.
   WaitForMultipleObjects( 2, hThreads, TRUE, INFINITE );

   // Close the thread handles
   CloseHandle( hThreads[0] );
   CloseHandle( hThreads[1] );

   // Delete the critical section
   DeleteCriticalSection( &g_CriticalSection );
}

Tool Tips
I really like doing tools tips in dialogs because there's almost no work after the initialization. I also prefer the Win32 API way (no MFC) because it's simpler to see what's going on. Just do the following in the WM_INITDIALOG handler for the dialog--
#include <DlgCtrlToolTip.h>

   // in the WM_INITDIALOG handler for the dialog
   DlgCtrlToolTip m_tt( hwndDialog, appInstance );
   m_tt.SetToolTipText( controlId, stringId, otherStringInstance );
On destroy of the parent all children are automatically destroyed.
On destroy of the owner all owned are automatically destroyed.

That is: a handle created specifying a parent or owner handle is automatically destroyed. To have independent windows, pass NULL for the parent window handle. An owned window is created using a parent window handle and specifying WS_CHILD.

See the source code here[h,cpp].


Version String
Here's a routine that gets the version string from any file's resource--

VersionString.h
VersionString.cpp


Execute and Wait
To start another application then wait for that application to finish, use the handle from CreateProcess() in a blocking call to WaitForSingleObject().

CPU Speed
Here's a way of calculating it. It is also stored in the registry but you
don't get it with Windows 95.

#pragma warning( disable: 4035 )
inline unsigned __int64 GetCycleCount()
{
 _asm
 {
  _emit 0x0F
  _emit 0x31
 }
}
#pragma warning( default: 4035 )


int GetCPUSpeed()
{
 const unsigned __int64 ui64StartCycle = GetCycleCount();
 Sleep( 1000 );
 return static_cast( ( GetCycleCount() - ui64StartCycle ) / 1000000 );
}

Best regards,
Mark

"Gary Fehr"  wrote in message
news:fEYy7.75$1L8.170720256@news.frii.net...
> Hi,
> Any way to programmatically get the CPU speed?
> Thanks,
> Gary

WinSock programming URLs
http://www.cyberport.com/~tangent/programming/winsock
http://www.sockets.com
http://www.sockaddr.com
http://www.stardust.com/winsock
http://cyberhipster.com/net/inetprog.htm#c
http://compnetworking.about.com/cs/programming

Setting System Time
You can set the system time by calling SetSystemTime() but how to update the display?
Broadcast WM_TIMECHANGE.

testing autorun.inf
See msdn article here

Messages-First and Last

WM_CREATE is guaranteed to be the first message that is sent to your windows procedure.

WM_NCDESTROY is guaranteed to be the last.