[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
Win32 API Code Snippets

(Win32 API) Code snippets

Page overview

  • How to: Obtain all window handles?
  • How to: obtain a window's text?
  • How to: get the last error?
  • Topic links

How to: Obtain all window handles?

Example to get a std::map of std::string and HWND.

  1. include <map>
  2. include <string>
  3. include <windows>
std::map<std::string,HWND> getWindows(const HWND& anyHandle) { std::map<std::string,HWND> myWindows; const int sizeBuffer = 100; char buffer[sizeBuffer]; HWND handle = GetWindow(anyHandle,GW_HWNDFIRST); while(handle!=0) { GetWindowText(handle,buffer,sizeBuffer); if (std::string(buffer)!="") myWindows[std::string(buffer)] = handle; handle = GetNextWindow(handle,GW_HWNDNEXT); } return myWindows; }


Note that window handles move in memory in time! So you cannot retrieve them once at the start of your program (thus making the std::map const).

How to: obtain a window's text?

Easier function around GetWindowText.

std::string getWindowText(const HWND& handle)
{
  const int sizeBuffer = 100;
  char buffer[sizeBuffer];
  GetWindowText(handle,buffer,sizeBuffer);
  const std::string windowText(buffer);
  return windowText;
}


How to: get the last error?

Easier function for around GetLastError

std::string getLastError()
{
  LPVOID lpMsgBuf;
  FormatMessage(
      FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
      0,
      GetLastError(),
      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
      (LPTSTR) &lpMsgBuf,
      0,
      0
  );
  //Transform to std::string
  const std::string lastError = (char*)lpMsgBuf; //A dirty cast!
  // Free the buffer.
  LocalFree( lpMsgBuf );
  //Return the std::string
  return lastError;
}


Topic links



last edited (May 20, 2007) by bilderbikkel, Number of views: 1683, Current Rev: 1

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.