old-new-win32api
Organized bookmarks to Win32API posts of Raymond Chen's blog "The Old New Thing".
The Old New Win32API
This page provides a list of links to subset of posts of Raymond Chen's famous blog The Old New Thing. The subset is limited mainly to Win32API and some COM-related stuff.
The reason why I maintain this page is that it often provides information which is missing on MSDN or which is described there in a cryptic way, and also because the blog is not easily searchable.
The links here are categorized by their topic instead of a chronological order. Sometimes, when appropriate, a single post may be put into multiple categories.
In some (quite rare) cases, links to other sources are included if they are found useful.
Disclaimer: I am not claiming authorship of any linked contents. This is only about hopefully useful organization of the great articles Raymond has written over the years.
Table of Contents
- Processes and Threads
- Synchronization
- DLLs
- Resources
- Application (as a whole)
HWND(General Point of View)- Top-Level Windows
- Controls
- Processing of Messages
- Specific Messages
- GDI
- Accessibility
- COM
- Declaring COM Interfaces
- COM Apartments
- COM Initialization
- COM Static Store
- COM Marshaling
- COM Error Handling
- COM Asynchronous Interfaces
- GUIDs
- COM Strings
- COM Variants
IUnknownIMonikerICallbackIContextMenuIFileDialogIMultiLanguageINamespaceWalkIStreamIVirtualDesktopManager- Clipboard
- Drag and Drop
- Enumeration
- Shell
- Uncategorized COM Stuff
- Memory
- Input and Output
- Security Permissions, Attributes and Identifiers
- Registry
- Strings and Locales
- NT Services
- Uncategorized
Processes and Threads
Processes
CreateProcessdoes not wait for the process to start- Why does the
CreateProcessfunction modify its input command line? - Why do people take a lock around
CreateProcesscalls? - Disabling the program crash dialog
- How do I pass a lot of data to a process when it starts up?
- What was the purpose of the
hPrevInstanceparameter toWinMain? - Is
RunAsInvokera secret, even higher UAC setting? - How do I prevent a child process from displaying the Windows Error Reporting dialog?
- How is it that
WriteProcessMemorysucceeds in writing to read-only memory? - Is it a good idea to let
WriteProcessMemorymanage the page protection for me? - How can I launch an unelevated process from my elevated process, redux
- How can I check the integrity level of my process?
- Is it true that raising a structured exception from a structured exception handler terminates the process?
- A more direct and mistake-free way of creating a process in a job object
Threads
- Invalid thread and process IDs
- Why does my thread handle suddenly go bad? All I did was wait on it!
- What happens if you simply return from the thread callback passed to
_beginthreadand_beginthreadex? - Why you should never suspend a thread
- The dangers of sleeping on a UI thread
- In pursuit of the message queue
- Enumerating threads in a process
- Win32 user interface work is inherently single-threaded
- How bad is it to delay closing a thread handle for a long time after the thread has exited?
- If I call
GetExitCodeThreadfor a thread that I know for sure has exited, why does it still saySTILL_ACTIVE? - Is there a problem with
CreateRemoteThreadon 64-bit systems? - Is the
TerminateThreadfunction synchronous? - Removing the
TerminateThreadfrom code that waits for a job object to empty - What is the point of
FreeLibraryAndExitThread? - What happens if I give contradictory values for the stack commit and stack reserve?
Thread Pools
- What exactly does the
msWindowLengthparameter toSetThreadpoolTimermean? - What’s the difference between
CreateTimerQueueTimerandSetThreadpoolTimer? - How to avoid accessing freed memory when canceling a thread pool callback
- Avoiding deadlocks when cancelling a thread pool callback, part 1: External callback data
- Avoiding deadlocks when cancelling a thread pool callback, part 2: Referring back to the containing object
- Gotcha: A threadpool periodic timer will not wait for the previous tick to complete
- Why am I getting an exception from the thread pool during process shutdown?
- What happens to the value returned from the function passed to
QueueUserWorkItem? - The mental model for
StartThreadpoolIo - How can I detect that a thread pool work item is taking too long?
- How can I close a thread pool and cancel all work that had been queued to it?
Thread Affinity of Objects
- Thread affinity of user interface objects, part 1: Window handles
- Thread affinity of user interface objects, part 2: Device contexts
- Thread affinity of user interface objects, part 3: Menus, icons, cursors, and accelerator tables
- Thread affinity of user interface objects, part 4: GDI objects and other notes on affinity
- Thread affinity of user interface objects, part 5: Object clean-up
- Thread affinity of user interface objects: Addendum
Thread Stack
- How can I expand my thread’s stack at runtime?
- Using fibers to expand a thread’s stack at runtime, part 1
- Using fibers to expand a thread’s stack at runtime, part 2
- Using fibers to expand a thread’s stack at runtime, part 3
- Using fibers to expand a thread’s stack at runtime, part 4
- Using fibers to expand a thread’s stack at runtime, part 5
- Using fibers to expand a thread’s stack at runtime, part 6
- Comparing fibers to threads for the purpose of expanding a thread’s stack at runtime
- Determining approximately how much stack space is available, part 1
- Determining approximately how much stack space is available, part 2
Fibers
- What happens to the fibers which ran on a thread when the thread exits?
- It's fine to use fibers, but everybody has to be on board with the plan
- Fibers aren’t useful for much any more; there’s just one corner of it that remains useful for a reason unrelated to fibers
Synchronization
- Understanding the consequences of
WAIT_ABANDONED - Windows keyed events, critical sections, and new Vista synchronization features
- Combining the work queue of distinct events, order not important, with an auto-reset event
- How fair are SRW locks, particularly when there are both readers and writers?
- You can use a file as a synchronization object, too
- Can I wait for a kernel event to become unsignaled?
- If the slim reader/writer lock (
SRWLOCK) doesn’t remember who the shared lock owner is, does that mean it’s okay to acquire it recursively?
WaitOnAddress()
WaitOnAddresslets you create a synchronization object out of any data variable, even a byte- Implementing a synchronization barrier in terms of
WaitOnAddress - Implementing a critical section in terms of
WaitOnAddress - Extending our critical section based on
WaitOnAddressto support timeouts - Comparing
WaitOnAddresswith futexes (futexi? futexen?) - Creating a semaphore from
WaitOnAddress - Creating a semaphore with a maximum count from
WaitOnAddress - Creating a manual-reset event from
WaitOnAddress - Creating an automatic-reset event from
WaitOnAddress
WaitForMultipleObjects() and Relatives
MsgWaitForMultipleObjectsand the queue state- You can call
MsgWaitForMultipleObjectswith zero handles - Pumping messages while waiting for a period of time
- Waiting for all handles with
MsgWaitForMultipleObjectsis a bug waiting to happen - Why does
WaitForMultipleObjectsreturnERROR_INVALID_PARAMETERwhen all the parameters look valid to me? - If more than one object causes a
WaitForMultipleObjectsto return, how do I find out about the other ones? - What’s the point of passing a never-signaled event to
MsgWaitForMultipleObjects?
Lock-Free Patterns
- Lock free many-producer/single-consumer patterns: A work queue with task coalescing
- Lock free many-producer/single-consumer patterns: A work queue where the last one wins
- Lock free many-producer/single-consumer patterns: A work queue of identical non-coalescable events
- Lock free many-producer/single-consumer patterns: A work queue of distinct events, order not important
- Lock free many-producer/single-consumer patterns: A work queue of distinct events, FIFO
- Lock free many-producer/single-consumer patterns: A work queue of distinct events, order not important, follow-up question
DLLs
- Don't trust the return address
- Why can't I
GetProcAddressa function I dllexport'ed? - What is the difference between
HINSTANCEandHMODULE? - Accessing the current module's
HINSTANCEfrom a static library LoadLibraryEx(DONT_RESOLVE_DLL_REFERENCES)is fundamentally flawed- Why are DLLs unloaded in the "wrong" order?
- How are DLL functions exported in 32-bit Windows?
- Exported functions that are really forwarders
- Rethinking the way DLL exports are resolved for 32-bit Windows
- Names in the import library are decorated for a reason
- What happens when you get dllimport wrong?
- Issues related to forcing a stub to be created for an imported function
- Allocating and freeing memory across module boundaries
- DLL forwarding is not the same as delay-loading
- What is DLL import hinting?
- What is DLL import binding?
- What is the point of
FreeLibraryAndExitThread? - A library loaded via
LOAD_LIBRARY_AS_DATAFILE(or similar flags) doesn't get to play in any reindeer module games - Could there be any problems with calling
GetModuleFileNameExon your own process? - How can I specify that my DLL should resolve a DLL dependency from the same directory that the DLL is in?
- After I made my DLL delay-load another DLL, my DLL has started crashing in its process detach code
- The different kinds of DLL planting
- Why does
GetModuleInfofail to produce an entry point for executables? - What does the
SizeOfImagemean in theMODULEINFOstructure? - How do I suppress the error box that appears when a
LoadLibraryfails?
DllMain()
- Some reasons not to do anything scary in your
DllMain - Another reason not to do anything scary in your
DllMain: Inadvertent deadlock - Some reasons not to do anything scary in your
DllMain, part 3 - The thread that gets the
DLL_PROCESS_DETACHnotification is not necessarily the one that got theDLL_PROCESS_ATTACH notification - How you might be loading a DLL during
DLL_PROCESS_DETACHwithout even realizing it - When
DLL_PROCESS_DETACHtells you that the process is exiting, your best bet is just to return without doing anything
Resources
- The Resource Compiler defaults to
CP_ACP, even in the face of subtle hints that the file is UTF-8 - The relationship between module resources and resource-derived objects in 32-bit Windows
- What's the difference between
FreeResourceand, say,DestroyAcceleratorTable - PE resources must be 4-byte aligned, but that doesn't stop people from trying other alignments
- How can I tell that somebody used the
MAKEINTRESOURCEmacro to smuggle an integer inside a pointer? - Horrifically nasty gotcha:
FindResourceandFindResourceEx
Bitmap and Icon Resources
- Why are device-independent bitmaps upside down?
- The format of bitmap resources
- The format of icon resources
- The format of icon resources, revisited
- The evolution of the ICO file format, part 1: Monochrome beginnings
- The evolution of the ICO file format, part 2: Now in color!
- The evolution of the ICO file format, part 3: Alpha-blended images
- The evolution of the ICO file format, part 4: PNG images
- How do I set the alpha channel of a GDI bitmap to 255?
Message String Resources
Dialog Templates
- On the difficulty of getting pixel-perfect layout in Win32 dialog templates
- The evolution of dialog templates - 32-bit Classic Templates
- The evolution of dialog templates - 32-bit Extended Templates
- The evolution of dialog templates - Summary
- The resource compiler will helpfully add window styles for you, but if you're building a dialog template yourself, you don't get that help
Menu Templates and Accelerator Resources
- The evolution of menu templates: Introduction
- The evolution of menu templates: 32-bit classic menus
- The evolution of menu templates: 32-bit extended menus
- The format of accelerator table resources
String Resources
- The format of string resources
LoadStringcan load strings with embedded nulls, but your wrapper function might not
Version Templates
- The evolution of version resources - 32-bit version resources
- The evolution of version resources - corrupted 32-bit version resources
Data and Custom Resources
Application (as a whole)
- Which windows appear in the
Alt+Tablist? - Windows Vista changed the
Alt+Taborder slightly - Win32 user interface work is inherently single-threaded
- When does
STARTF_USESHOWWINDOWoverride the parameter passed toShowWindow? WaitForInputIdleshould really be calledWaitForProcessStartupCompleteWaitForInputIdlewaits for any thread, which might not be the thread you care about- What are the conventions for managing standard handles?
- Standard handles are really meant for single-threaded programs
- If only DLLs can get
DllMainnotifications, how can an EXE receive a notification when a thread is created (for example)?
Command Line
- The first word on the command line is the program name only by convention
- How is the
CommandLineToArgvWfunction intended to be used? - What's up with the strange treatment of quotation marks and backslashes by
CommandLineToArgvW
Taskbar
- How do I prevent users from pinning my program to the taskbar?
- Instead of creating something and then trying to hide it, simply don't create it in the first place (tray icon)
- What if my application is really two applications bundled into a single file, and I want them collected into two groups on the taskbar in Windows 7?
- How do I customize how my application windows are grouped in the Taskbar?
- Display an overlay on the taskbar button
- Display control buttons on your taskbar preview window
- Display a custom thumbnail for your application (and while you're at it, a custom live preview)
- How can I query the location of the taskbar on secondary monitors?
- How did that program manage to pin itself to my taskbar when I installed it?
- What if I have two programs that are logically a single application, and I want them to be treated as a single group on the taskbar?
- Why does the taskbar icon for grouped windows change to something weird?
HWND (General Point of View)
- What does it mean for a window to be Unicode?
- How can I get the actual window procedure address and not a thunk?
- What are these strange values returned from
GWLP_WNDPROC? - The bonus window bytes at
GWLP_USERDATA - What is the difference between
WM_DESTROYandWM_NCDESTROY? - Sending a window a
WM_DESTROYmessage is like prank calling somebody pretending to be the police - The secret life of
GetWindowText - Why are the rules for
GetWindowTextso weird? - Painting only when your window is visible on the screen
- Determining whether your window is covered
- Obtaining a window's size and position while it is minimized
- Why does calling
SetForegroundWindowimmediately followed byGetForegroundWindownot return the same window back? - How does Windows decide whether a newly-created window should use LTR or RTL layout?
Windows Hierarchy
- What's so special about the desktop window?
- What is the window nesting limit?
- What's the difference between
HWND_TOPandHWND_TOPMOST? - A window can have a parent or an owner but not both
- Why does my control send its notifications to the wrong window after I reparent it?
WindowFromPoint,ChildWindowFromPoint,RealChildWindowFromPoint, when will it all end?GetParent, just as confusing asEnumClaw, but it's an actual function! (GetAncestor(),GetWindow())- Having an owner window from another process is tricky, but it's sometimes the right thing to do
- What is the documentation for
SetParenttrying to tell me about synchronizing the UI state? - Demonstrating what happens when a parent and child window have different UI states
- Getting a parent and child window to have the same UI states
Window Styles
- Which window style bits belong to whom?
- How do I indicate that I want my window to follow right-to-left layout rules?
- Why isn't my transparent static control transparent? (
WS_EX_TRANSPARENT) - Like the cake,
WS_EX_TRANSPARENTis a lie, or at least not the entire truth - I used
WS_EX_COMPOSITEDto get rid of my redrawing flicker, but it resulted in sluggish response - How can I use
WS_CLIPCHILDRENand still be able to draw a control with a transparent background?
Window Classes
- What is the
HINSTANCEpassed toCreateWindowandRegisterClassused for? - Using the wrong
HINSTANCEinRegisterClassis like identity theft - If the
RegisterClassfunction takes ownership of the custom background brush, why is it leaking? - Changing a window class affects all windows which belong to that class
- What does
CS_SAVEBITSdo? - What does the
CS_OWNDCclass style do? - What does the
CS_CLASSDCclass style do? - Modifying the
CS_NOCLOSEstyle does affect all windows of the class, just not necessarily in an immediately noticeable way - Why does
PrintWindowhateCS_PARENTDC? Because EVERYBODY hatesCS_PARENTDC! - Why does
PrintWindowhateCS_PARENTDC? redux - Safer subclassing
- Private classes, superclassing, and global subclassing
- What makes
RealGetWindowClassso much more real thanGetClassName? - Why does
CreateWindowExtake the extended style parameter as its first parameter instead of its last? - When should I use
CS_GLOBALCLASS? - How unique must the uIdSubclass parameter be when I call
SetWindowSubclass?
Top-Level Windows
Window Frame and Caption
- Getting a custom right-click menu for the caption icon
- Drawing an active-looking caption even when not active
- How do I suppress full window drag/resize for just one window?
- How do I switch a window between normal and fullscreen?
- How do I enable and disable the minimize, maximize, and close buttons in my caption bar?
- Getting the location of the Close button in the title bar
- Getting the location of the Close button in the title bar, from Windows 2000 or Windows XP
- Why are the dimensions of a maximized window larger than the monitor?
- Creating a window that can be resized in only one direction
- Why don't you forward
WM_GETMINMAXINFOand clamp the results?
DWM
- Why doesn't my program receive the
WM_DWMSENDICONICTHUMBNAILmessage when I ask for an iconic representation? - The
MARGINSparameter to theDwmExtendFrameIntoClientAreafunction controls how far the frame extends into the client area - How do I suppress the default animation that occurs when I hide or show a window?
- Display a custom thumbnail for your application (and while you're at it, a custom live preview)
- How can I detect that my window has been suppressed from the screen by the shell? ("window cloaking")
Dialogs
- Why can't I create my dialog box? Rookie mistake #1
- Why can't I create my dialog box? Rookie mistake #2
- Returning values from a dialog procedure
- A different type of dialog procedure
- Another different type of dialog procedure
- The default answer to every dialog box is "Cancel"
- Rotating the Z-order
- Using the
TABkey to navigate in non-dialogs - Using the
TABkey to navigate in non-dialogs, redux - Preventing edit control text from being autoselected in a dialog box
- Those who do not understand the dialog manager are doomed to reimplement it, badly
- Other tricks with
WM_GETDLGCODE GetDialogBaseUnitsis a crock- Why isn’t
MapDialogRectmapping dialog rectangles? - Why are dialog boxes initially created hidden?
- What's the deal with the
DS_SHELLFONTflag? - Why does
DS_SHELLFONT = DS_FIXEDSYS | DS_SETFONT? - How to set focus in a dialog box
- Never leave focus on a disabled control
- A subtlety in restoring previous window position
- Things you already know: How do I wait until my dialog box is displayed before doing something?
- What does
TranslateAcceleratordo? - If I have a modeless dialog box with custom accelerators, which should I call first:
IsDialogMessageorTranslateAccelerator - Gentle reminder: On a dialog box, do not give OK and Cancel accelerators
- Why are accelerators for hidden controls still active?
- How do I make my accelerators apply only when used in the main window and not when the user is using a modeless dialog?
- Why doesn't the
TABkey work on controls I've marked asWS_TABSTOP? - You can't use the
WM_USERmessage in a dialog box - How can I make a dialog box right-to-left at runtime?
- How does the dialog manager calculate the average width of a character?
Nested and Embedded Dialogs
- What is the
DS_CONTROLstyle for? - More notes on use of the
DS_CONTROLstyle - It's not a good idea to give multiple controls on a dialog box the same ID
- When embedding a dialog inside another, make sure you don't accidentally create duplicate control IDs
- When the default pushbutton is invoked, the invoke goes to the top-level dialog
Common Dialogs
- Why doesn't my
MessageBoxwrap at the right location? - How do I customize the Favorite Links section of the File Open dialog?
- Why does the common file dialog change the current directory?
- You can filter the Common File dialog with wildcards
- How do I display the Find Printers dialog programmatically?
- Why doesn't the Open Files list in the Shared Folders snap-in show all my open files?
- A common control for associating extensions is well overdue
- Filtering the folders that appear in the Browse for Folder dialog
- Opening the classic folder browser dialog with a specific folder preselected
- Why does the common file save dialog create a temporary file and then delete it?
- Customing the standard color-picker dialog
- How do I set the initial directory of the File Open dialog to a virtual directory?
- When I select multiple files in the File Open dialog, why does the last item come first?
- I set the
OFN_NONETWORKBUTTONoption in theOPENFILENAMEstructure, but it has no effect on the network item in the navigation pane - How do I add custom controls to the common file open or file save dialogs?
- How can I get my
FileSavePickerto open in the same folder that was picked by theFileOpenPickerorFolderPicker? (win32/COM equivalent mentioned at the end of the post)
Control Navigation
- Using the
TABkey to navigate in non-dialogs - Using the
TABkey to navigate in non-dialogs, redux - Managing the UI state of accelerators and focus rectangles
- Custom navigation in dialog boxes, redux
- Dialog boxes return focus to the control that had focus when you last switched away; how do I get in on that action for my own windows?
- How can I create a non-circular tab order, or some other type of custom ordering in my Win32 dialog?
Dialog Manager
- The dialog manager, part 1: Warm-ups
- The dialog manager, part 2: Creating the frame window
- The dialog manager, part 3: Creating the controls
- The dialog manager, part 4: The dialog loop
- The dialog manager, part 5: Converting a non-modal dialog box to modal
- The dialog manager, part 6: Subtleties in message loops
- The dialog manager, part 7: More subtleties in message loops
- The dialog manager, part 8: Custom navigation in dialog boxes
- The dialog manager, part 9: Custom accelerators in dialog boxes
Modality
- The correct order for disabling and enabling windows
- Modality, part 1: UI-modality vs code-modality
- Modality, part 2: Code-modality vs UI-modality
- Modality, part 3: The
WM_QUITmessage - Modality, part 4: The importance of setting the correct owner for modal UI
- Modality, part 5: Setting the correct owner for modal UI
- Modality, part 6: Interacting with a program that has gone modal
- Modality, part 7: A timed
MessageBox, the cheap version - Modality, part 8: A timed
MessageBox, the better version - Modality, part 9: Setting the correct owner for modal UI, practical exam
- Thread messages are eaten by modal loops
- Rescuing thread messages from modal loops via message filters
Property Sheets
- What other effects does
DS_SHELLFONThave on property sheet pages? PSM_ISDIALOGMESSAGEis to modeless property sheets asIsDialogMessageis to modeless dialog boxes- You can extend the
PROPSHEETPAGEstructure with your own bonus data - The
PSN_SETACTIVEnotification is sent each time your wizard page is activated - Appending additional payload to a
PROPSHEETPAGEstructure - How do I pass an array of variable-sized
PROPSHEETPAGEstructures to PropertySheet?
Controls
Animation Controls
- Limitations of the shell animation control
- Why does the version 6 animation control not use a background thread?
Buttons
- What's the
BS_PUSHLIKEbutton style for? (Don't use, it's completely obsolete nowadays. Use check box or radio button instead.)
Combo Boxes
- Speeding up adding items to a combobox or listbox (
WM_SETREDRAW)
Edit Controls
- What's the deal with the
EM_SETHILITEmessage? - Preventing edit control text from being autoselected in a dialog box
- How do I suppress the
CapsLockwarning on password edit controls? - The early history of the
ES_NUMBERedit control style - How do I allow negative numbers with the
ES_NUMBERedit control style? - How do I permit a minus sign to be entered into my edit control, but only if it’s the first character?
List Views
- Positioned vs. non-positioned listview views
- Displaying infotips for folded and unfolded listview items
- Computing listview infotips in the background
- What's the difference between
LVM_HITTESTandLVM_INSERTMARKHITTEST? - Why is there an
LVN_ODSTATECHANGEDnotification when there's already a perfectly goodLVN_ITEMCHANGEDnotification? - Creating a listview with checkboxes on some items but not others
- How can I programmatically resize a listview column to fit its contents?
- How do I create a disabled checkbox for a listview item?
- Speeding up adding items to a combobox or listbox (
WM_SETREDRAW)
Rich Text Controls
The history of the RichEdit control from Murray Sargent(The post is just a (broken) link to https://blogs.msdn.microsoft.com/murrays/2006/10/19/some-richedit-history/)- How do I load an entire file into a rich text control?
- How do I put more than 32,000 characters into a rich text control?
- How do I print the contents of a rich text control?
Scrollbars
- The scratch program
- Scrollbars, part 2
- Scrollbars, part 3: Optimizing the paint cycle
- Scrollbars, part 4: Adding a proportional scrollbar
- Likely part 5: Keyboard accessibility for scrollbars
- Addendum to part 5: A subtlety in the keyboard code
- Scrollbars part 6 - The wheel
- Scrollbars part 7 - Integrality
- Scrollbars part 8 - Integral interactive resizing
- Scrollbars part 9 - Maintaining the metaphor
- Scrollbars part 10 - Towards a deeper understanding of the
WM_NCCALCSIZEmessage - Scrollbars part 11: Towards an even deeper understanding of the
WM_NCCALCSIZEmessage - Answers to exercise from Scrollbars Part 11
- Scrollbars part 12: Applying
WM_NCCALCSIZEto our scrollbar sample - Scrollbars redux: Part 12
- There are two types of scrollbars
- Why was
WHEEL_DELTAchosen to be 120 instead of a much more convenient value like 100 or even 10? - Why does setting the horizontal scroll bar range for the first time also set the vertical range, and vice versa?
- Autoscrolling on drag, part 1: Basic implementation
- Autoscrolling on drag, part 2: Why does scrolling go faster if I wiggle the mouse?
- Autoscrolling on drag, part 3: Dynamic autoscroll based on mouse position
- Autoscrolling on drag, part 4: Dynamic autoscroll based on escape velocity
- Autoscrolling on drag, part 5: Adding wiggle-to-scroll to escape velocity
Static Controls
Tab Controls
- How should I create controls on my dialog box that has a tab control?
- How am I supposed to create children of the Win32 tab control?
Toolbars
- Why are there both
TBSTYLE_EX_VERTICALandCCS_VERT? - How do I create a toolbar that sits in the taskbar?
- How do I create a right-aligned toolbar button?
- Creating custom tasks on a jump list
Tooltips
- Coding in-place tooltips
- Using custom-draw in tooltips to adjust the font
- Multiplexing multiple tools into one in a tooltip
- Generating tooltip text dynamically
- Why can't I display a tooltip for a disabled window?
- Over-documenting
TTM_RELAYEVENTand why it results in a one-second periodic timer running as long as the tooltip is visible
Trackbars
- Adding a
Ctrl+arrow accelerator for moving the trackbar by just one unit, part 1: Initial plunge - Adding a
Ctrl+arrow accelerator for moving the trackbar by just one unit, part 2: Second try - How do I prevent users from using the mouse to drag the trackbar thumb to positions that aren’t multiples of five? Part 1: Reframe the problem
- How do I prevent users from using the mouse to drag the trackbar thumb to positions that aren’t multiples of five? Part 2: Nudging the thumb position
Tree-List Views
- The
TVS_CHECKBOXESstyle is quirky, which is a polite way of saying that it is crazy - Beware of the leaked image list when using the
TVS_CHECKBOXESstyle - Creating tree view check boxes manually: A simple state image list
- Creating tree view check boxes manually: Responding to clicks
- Creating tree view check boxes manually: Themed check boxes
- Tree view check boxes: A sordid history
- Tree view check boxes: The extended check box states
Processing of Messages
- Which message numbers belong to whom?
- The various ways of sending a message
- Broadcasting user-defined messages
- When can a thread receive window messages?
- What's the difference between
GetKeyStateandGetAsyncKeyState? - Thread messages are eaten by modal loops
- Rescuing thread messages from modal loops via message filters
- The dangers of filtering window messages
- You can't simulate keyboard input with
PostMessage - Pumping messages while waiting for a period of time
- In pursuit of the message queue
- No, really, you need to pass all unhandled messages to
DefWindowProc - Even if you have code to handle a message, you're allowed to call
DefWindowProc, because you were doing that anyway after all - What were
Get/SetMessageExtraInfoever used for? - Why is
GetWindowLongPtrreturning a garbage value on 64-bit Windows? TrackMouseEventtracks mouse events in your window, but only if the events belong to your window- Don't forget to include the message queue in your lock hierarchy
- What happens to a sent message when
SendMessageTimeoutreaches its timeout? - Why can't I
PostMessagetheWM_COPYDATAmessage, but I canSendMessageTimeoutit with a tiny timeout? - Even though mouse-move, paint, and timer messages are generated on demand, it's still possible for one to end up in your queue
- Posted messages are processed ahead of input messages, even if they were posted later
- What kind of messages can a message-only window receive?
- If the prototypes of
DispatchMessageAandDispatchMessageWare identical, why have both? - Those who do not understand the dialog manager are doomed to reimplement it, badly
- How can I trigger a recalc of the mouse cursor after I changed some of my internal application state?
- How can I trigger a recalc of the mouse cursor after I changed some of my internal application state?, follow-up
GetQueueStatusand the queue state
Hooking
- What is the
HINSTANCEpassed toSetWindowsHookExused for? - How can I get notified when the cursor changes?
- What does the thread parameter to
SetWindowsHookExactually mean? - Why does
SetFocusfail without telling me why?
Specific Messages
Notifications
- What's the difference between the
wParamof theWM_NOTIFYmessage and theidFromin theNMHDRstructure. - Restating the obvious about the
WM_COMMANDmessage - Restating the obvious about the
WM_NOTIFYmessage
Window Construction and Destruction
- What is the difference between
WM_DESTROYandWM_NCDESTROY? - How can I determine the reason why my window is closing? (
WM_CLOSE)
Window Geometry Messages
- Use
WM_WINDOWPOSCHANGEDto react to window state changes - Use
WM_WINDOWPOSCHANGINGto intercept window state changes
Window Painting Messages
- Paint messages will come in as fast as you let them (
WM_PAINT) - What happens if I don't paint when I get a
WM_PAINTmessage? - What is the implementation of
WM_PRINTCLIENT? - There's a default implementation for
WM_SETREDRAW, but you might be able to do better - Speeding up adding items to a combobox or listbox (
WM_SETREDRAW) - Using
WM_SETREDRAWto speed up adding a lot of elements to a control
Window Focus Messages
WM_KILLFOCUSis the wrong time to do field validation- The dangers of playing focus games when handling a
WM_KILLFOCUSmessage - Why doesn't the
MoveWindowfunction generate theWM_GETMINMAXINFOmessage?
Keyboard Messages
Mouse Messages
- Why is there no
WM_MOUSEENTERmessage? - Why do I get spurious
WM_MOUSEMOVEmessages? - Sure, I can get spurious
WM_MOUSEMOVEmessages, but why do they keep streaming in? - How do I get mouse messages faster than
WM_MOUSEMOVE? - Logical consequences of the way Windows converts single-clicks into double-clicks
- Implementing higher-order clicks
- How slow do you have to slow-double-click for it to be a rename?
- How can I prevent the mouse from moving in response to touch input?
Dialog Messages
- Those who do not understand the dialog manager are doomed to reimplement it, badly
- Managing the UI state of accelerators and focus rectangles (
WM_CHANGEUISTATE,WM_QUERYUISTATEandWM_UPDATEUISTATE) - Untangling the confusingly-named
WM_UPDATEUISTATEandWM_CHANGEUISTATEmessages - Who sends the initial
WM_UPDATEUISTATEmessage? - How can I prevent the keyboard focus rectangle from appearing on a control I created?
- Other tricks with
WM_GETDLGCODE - How do I prevent multi-line edit controls from eating the Enter key?
- Why do
DLGC_WANTALLKEYSandDLGC_WANTMESSAGEhave the same value?
Other Window Messages
- The dangers of messing with activation when handling a
WM_ACTIVATEmessage - Why does my window get a
WM_ACTIVATEmessage when it isn't active? - A timed context menu (
WM_CANCELMODE) - Pitfalls in handling the
WM_CONTEXTMENUmessage (WM_CONTEXTMENU) WM_NCHITTESTis for hit-testing, and hit-testing can happen for reasons other than the mouse being over your window- How likely is it that a window will receive a
WM_NULLmessage out of the blue? (WM_NULL) - Why is there a special
PostQuitMessagefunction? (WM_QUIT) - How does
PostQuitMessageknow which thread to post the quit message to? (WM_QUIT) - Who is responsible for destroying the font passed in the
WM_SETFONTmessage? (WM_SETFONT) - When I send a
WM_GETFONTmessage to a window, why don't I get a font? (WM_GETFONT) - If my
WM_TIMERhandler takes longer than the timer period, will my queue fill up withWM_TIMERmessages? - Killing a window timer prevents the
WM_TIMERmessage from being generated for that timer, but it doesn't retroactively remove ones that were already generated
System Messages
- If one program blocks shutdown, then all programs block shutdown (
WM_QUERYENDSESSION,WM_ENDSESSION) - Why do I have to return this goofy value for
WM_DEVICECHANGE? (WM_DEVICECHANGE) - Windows doesn't close windows when a user logs off; that's your call (
WM_ENDSESSION) - Once you return from the
WM_ENDSESSIONmessage, your process can be terminated at any time (WM_ENDSESSION)
GDI
- Why are
RECTs endpoint-exclusive? - Can you create an information context for the display?
- What does the
CS_OWNDCclass style do? - What does the
CS_CLASSDCclass style do? - How do you detect "Large Fonts"? (DPI)
- Drawing a monochrome bitmap with transparency
- Let GDI do your RLE compression for you
- The mysterious stock bitmap: There's no way to summon it, but it shows up in various places
- Why is my icon being drawn at the wrong size when I call
DrawIcon? - You must flush GDI operations when switching between direct access and GDI access, and direct access includes other parts of GDI
- How do I get the dimensions of a cursor or icon?
- What are the dire consequences of not selecting objects out of my DC?
- Of what use is the
RDW_INTERNALPAINTflag? - Functions that return GDI regions rarely actually return regions
- Color-aware ClearType requires access to fixed background pixels, which is a problem if you don't know what the background pixels are, or if they aren't fixed
- What is the correct way of using
SaveDCandRestoreDC? - How are
BitBltraster opcodes calculated? - Notes on
DrawTextand tab stops - Why doesn’t
GetTextExtentPointreturn the correct extent for strings containing tabs? - Why are there trivial functions like
CopyRectandEqualRect? - More on trivial functions like
CopyRectandEqualRect - What are the consequences of increasing the per-process GDI handle limit?
- The focus rectangle says, “I’m not orange. I’m just drawn that way.”
Cursors
- The effect of
SetCursorlasts only until the nextSetCursor - What can or should I do with the cursor handle returned by
SetCursor? - What is the deal with the
SM_CXCURSORsystem metric? - How do I find out the size of the mouse cursor?
Brushes
- The hollow brush
- Other uses for bitmap brushes
- What is the DC brush good for?
- I know I can change the color of the DC pen, but what about the other attributes?
- How can I extract the color from a solid color GDI brush?
Pens
- Is there a difference between creating a null pen with
CreatePenand just using the stock null pen?
Bitmaps
DIB
- A survey of the various ways of creating GDI bitmaps with predefined data
- Blitting between color and monochrome DCs
- Manipulating the DIB color table for fun and profit
- Using DIB sections to perform bulk color mapping
- The fun and profit of manipulating the DIB color table can be done without having to modify it
- Separating the metadata from the DIB pixels: Precalculating the
BITMAPINFO - Separating the metadata from the DIB pixels: Changing the raster operation
- The disembodiment of DIBs from the DIB section
- What is the
hSectionparameter toCreateDIBSectionfor?
LockWindowUpdate()
- What does
LockWindowUpdatedo? - How is
LockWindowUpdatemeant to be used? - With what operations is
LockWindowUpdatemeant to be used? - With what operations is
LockWindowUpdatenot meant to be used? - Final remarks on
LockWindowUpdate
Painting Standard Elements
- Rendering standard Windows elements
- Rendering menu glyphs is slightly trickier
- What states are possible in a
DRAWITEMSTRUCTstructure?
UXTHEME.DLL
BeginBufferedPaint: It's not just for buffered painting any more- How do
IsThemeActive,IsAppThemed, andIsCompositionActivediffer? - How do I get the tabbed dialog effect on my own custom tabbed dialog?
- How do I revert a control back to its default theme?
Multiple Monitors
- For better performance, set all your monitors to the same color format
- How do I get a handle to the primary monitor?
- Why does the primary monitor have
(0,0)as its upper left coordinate? - How do I get the color depth of the screen?
- How does the window manager adjust
ptMaxSizeandptMaxPositionfor multiple monitors?
Accessibility
- Accessibility is not just for people with disabilities
- How to retrieve text under the cursor (mouse pointer)
- How do I set an accessible name on an unlabeled control?
- How can I get notified when some other window is destroyed?
- Using accessibility to monitor windows as they come and go
- How can I write a program that monitors another window for a title change?
- How can I write a program that monitors another window for a change in size or position?
COM
Declaring COM Interfaces
- The macros for declaring COM interfaces, revisited: C version
- The macros for declaring COM interfaces, revisited: C++ version
- The macros for declaring COM interfaces, revisited: C++ implementation
- The oracle always tells the truth, even when it is wrong: COM method calls with a user-defined type as a return value (on problems of COM interfaces called from C code)
- The COM interface contract rules exist for a reason
- Giving a single object multiple COM identities, part 1
- Giving a single object multiple COM identities, part 2
- Giving a single object multiple COM identities, part 3
- Giving a single object multiple COM identities, part 4
- How do I consume raw COM interfaces from a Windows Runtime metadata file?
COM Apartments
- The dreaded "main" threading model
- A slightly less brief introduction to COM apartments (but it’s still brief)
- Yo dawg, I hear you like COM apartments, so I put a COM apartment in your COM apartment so you can COM apartment while you COM apartment
- What kind of apartment is the private apartment I created via
CLSID_ContextSwitcher? - Setting up private COM contexts to allow yourself to unload cleanly
- How do you get into a context via
IContextCallback::ContextCallback? - Using contexts to return to a COM apartment later
- What do the output values from
CoGetApartmentTypemean? - User interface code + multi-threaded apartment = death
- Other problems traced to violating COM single-threaded apartment rules in the shell
- What’s the point of
APTTYPE_CURRENT? I mean, of course I’m current. - How do I get a foothold in the neutral apartment?
- What is so special about the Application STA?
- What does it mean when a call fails with
0x8000001F = RO_E_BLOCKED_CROSS_ASTA_CALL?
COM Initialization
- What does the
COINIT_SPEED_OVER_MEMORYflag toCoInitializeExdo? - Crashing in COM after I call
CoUninitialize, how can COM be running after it is uninitalized?
COM Static Store
- The COM static store, part 1: Introduction
- The COM static store, part 2: Race conditions in setting a singleton
- The COM static store, part 3: Avoiding creation of an expensive temporary when setting a singleton
- The COM static store, part 4: Aggregating into a single object
- The COM static store, part 5: Using COM weak references
- The COM static store, part 6: Using C++ weak references
COM Marshaling
- What is COM marshaling and how do I use it?
- On proper handling of buffers in COM and RPC methods
- What are the rules for
CoMarshalInterThreadInterfaceInStreamandCoGetInterfaceAndReleaseStream? - What are the rules for
CoMarshalInterfaceandCoUnmarshalInterface? CoGetInterfaceAndReleaseStreamdoes not mix with smart pointers- The COM marshaller uses the COM task allocator to allocate and free memory
- Why do I get a
QueryInterface(IID_IMarshal)and then nothing? - We batched up our COM requests and return a single stream of results, but the performance is still slow
- What are the various usage patterns for manually-marshaled interfaces?
- An initial look at the mechanics of how COM marshaling is performed
- https://devblogs.microsoft.com/oldnewthing/20220616-00/?p=106757
- Writing a marshal-by-value marshaler, part 1
- Writing a marshal-by-value marshaler, part 2
- Writing a compound marshaler
- Understanding the marshaling flags: The free-threaded marshaler
COM Error Handling
- What happens to my COM server-side object when clients die unexpectedly?
- Why does COM require output pointers to be initialized even on failure?
- How do I convert an
HRESULTto a Win32 error code? - How can I tell the WIL
RETURN_IF_FAILEDmacro that some errors are ignorable? - Do not overload the
E_NOINTERFACEerror - What does it mean when a call fails with
0x8000001F = RO_E_BLOCKED_CROSS_ASTA_CALL? - What does it mean when my cross-thread COM call fails with
RPC_E_SYS_CALL_FAILED? - Understanding a mysterious
RPC_E_WRONGTHREADexception when we’re on the right thread
COM Asynchronous Interfaces
- COM asynchronous interfaces, part 1: The basic pattern
- COM asynchronous interfaces, part 2: Abandoning the operation
- COM asynchronous interfaces, part 3: Abandoning the operation after a timeout
- COM asynchronous interfaces, part 4: Doing work while waiting for the asynchronous operation
- COM asynchronous interfaces, part 5: The unreliable server
- COM asynchronous interfaces, part 6: Learning about completion without polling
- COM asynchronous interfaces, part 7: Being called directly when the operation completes
- COM asynchronous interfaces, part 8: Asynchronous release, the problems
- COM asynchronous interfaces, part 9: Asynchronous release, assembling a solution
GUIDs
- What's the difference between
UuidFromString,IIDFromString,CLSIDFromString,GUIDFromString... - What is the difference between
UuidToString,StringFromCLSID,StringFromIID, andStringFromGUID2? - Why are there four functions for parsing strings into GUIDs, and why are they in three different DLLs?
- Why does COM express GUIDs in a mix of big-endian and little-endian? Why can’t it just pick a side and stick with it?
COM Strings
- Why is there a
BSTRcache anyway? - Raymond’s complete guide to
HSTRINGsemantics - What is the correct way of using the string buffer returned by the
WindowsPreallocateStringBufferfunction?
COM Variants
- What’s the difference between
VARIANTandVARIANTARG? - Nasty gotcha:
VarCmpvsVariantCompare - Why can’t
VarDateFromStrparse back a Hungarian date that was generated byVarBstrFromDate?
IUnknown
more like this
stylo
Stylo est un éditeur de textes pour articles scientifiques en sciences humaines et sociales.