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
IUnknown
IMoniker
ICallback
IContextMenu
IFileDialog
IMultiLanguage
INamespaceWalk
IStream
IVirtualDesktopManager
- 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
CreateProcess
does not wait for the process to start- Why does the
CreateProcess
function modify its input command line? - Why do people take a lock around
CreateProcess
calls? - 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
hPrevInstance
parameter toWinMain
? - Is
RunAsInvoker
a secret, even higher UAC setting? - How do I prevent a child process from displaying the Windows Error Reporting dialog?
- How is it that
WriteProcessMemory
succeeds in writing to read-only memory? - Is it a good idea to let
WriteProcessMemory
manage the page protection for me? - How can I launch an unelevated process from my elevated process, redux
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
_beginthread
and_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
GetExitCodeThread
for a thread that I know for sure has exited, why does it still saySTILL_ACTIVE
? - Is there a problem with
CreateRemoteThread
on 64-bit systems? - Is the
TerminateThread
function synchronous? - Removing the
TerminateThread
from 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
msWindowLength
parameter toSetThreadpoolTimer
mean? - What’s the difference between
CreateTimerQueueTimer
andSetThreadpoolTimer
? - 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?
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()
WaitOnAddress
lets 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
WaitOnAddress
to support timeouts - Comparing
WaitOnAddress
with 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
MsgWaitForMultipleObjects
and the queue state- You can call
MsgWaitForMultipleObjects
with zero handles - Pumping messages while waiting for a period of time
- Waiting for all handles with
MsgWaitForMultipleObjects
is a bug waiting to happen - Why does
WaitForMultipleObjects
returnERROR_INVALID_PARAMETER
when all the parameters look valid to me? - If more than one object causes a
WaitForMultipleObjects
to 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
GetProcAddress
a function I dllexport'ed? - What is the difference between
HINSTANCE
andHMODULE
? - Accessing the current module's
HINSTANCE
from 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
GetModuleFileNameEx
on 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
GetModuleInfo
fail to produce an entry point for executables? - What does the
SizeOfImage
mean in theMODULEINFO
structure?
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_DETACH
notification is not necessarily the one that got theDLL_PROCESS_ATTACH notification
- How you might be loading a DLL during
DLL_PROCESS_DETACH
without even realizing it - When
DLL_PROCESS_DETACH
tells 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
FreeResource
and, 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
MAKEINTRESOURCE
macro to smuggle an integer inside a pointer? - Horrifically nasty gotcha:
FindResource
andFindResourceEx
Bitmap and Icon Resources
- Why are device-independent bitmaps upside down?
- The format of bitmap resources
- The format of icon resources
- 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
LoadString
can 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+Tab
list? - Windows Vista changed the
Alt+Tab
order slightly - Win32 user interface work is inherently single-threaded
- When does
STARTF_USESHOWWINDOW
override the parameter passed toShowWindow
? WaitForInputIdle
should really be calledWaitForProcessStartupComplete
WaitForInputIdle
waits 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
DllMain
notifications, 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
CommandLineToArgvW
function 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_DESTROY
andWM_NCDESTROY
? - Sending a window a
WM_DESTROY
message is like prank calling somebody pretending to be the police - The secret life of
GetWindowText
- Why are the rules for
GetWindowText
so 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
SetForegroundWindow
immediately followed byGetForegroundWindow
not return the same window back?
Windows Hierarchy
- What's so special about the desktop window?
- What is the window nesting limit?
- What's the difference between
HWND_TOP
andHWND_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
SetParent
trying 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_TRANSPARENT
is a lie, or at least not the entire truth - I used
WS_EX_COMPOSITED
to get rid of my redrawing flicker, but it resulted in sluggish response - How can I use
WS_CLIPCHILDREN
and still be able to draw a control with a transparent background?
Window Classes
- What is the
HINSTANCE
passed toCreateWindow
andRegisterClass
used for? - Using the wrong
HINSTANCE
inRegisterClass
is like identity theft - Changing a window class affects all windows which belong to that class
- What does
CS_SAVEBITS
do? - What does the
CS_OWNDC
class style do? - What does the
CS_CLASSDC
class style do? - Modifying the
CS_NOCLOSE
style does affect all windows of the class, just not necessarily in an immediately noticeable way - Why does
PrintWindow
hateCS_PARENTDC
? Because EVERYBODY hatesCS_PARENTDC
! - Why does
PrintWindow
hateCS_PARENTDC
? redux - Safer subclassing
- Private classes, superclassing, and global subclassing
- What makes
RealGetWindowClass
so much more real thanGetClassName
? - Why does
CreateWindowEx
take the extended style parameter as its first parameter instead of its last?
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_GETMINMAXINFO
and clamp the results?
DWM
- Why doesn't my program receive the
WM_DWMSENDICONICTHUMBNAIL
message when I ask for an iconic representation? - The
MARGINS
parameter to theDwmExtendFrameIntoClientArea
function 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
TAB
key to navigate in non-dialogs - Using the
TAB
key 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
GetDialogBaseUnits
is a crock- Why isn’t
MapDialogRect
mapping dialog rectangles? - Why are dialog boxes initially created hidden?
- What's the deal with the
DS_SHELLFONT
flag? - 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
TranslateAccelerator
do? - If I have a modeless dialog box with custom accelerators, which should I call first:
IsDialogMessage
orTranslateAccelerator
- 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
TAB
key work on controls I've marked asWS_TABSTOP
? - You can't use the
WM_USER
message in a dialog box - How can I make a dialog box right-to-left at runtime?
Nested and Embedded Dialogs
- What is the
DS_CONTROL
style for? - 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
MessageBox
wrap 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_NONETWORKBUTTON
option in theOPENFILENAME
structure, 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?
Control Navigation
- Using the
TAB
key to navigate in non-dialogs - Using the
TAB
key 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_QUIT
message - 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_SHELLFONT
have on property sheet pages? PSM_ISDIALOGMESSAGE
is to modeless property sheets asIsDialogMessage
is to modeless dialog boxes- You can extend the
PROPSHEETPAGE
structure with your own bonus data - The
PSN_SETACTIVE
notification is sent each time your wizard page is activated - Appending additional payload to a
PROPSHEETPAGE
structure - How do I pass an array of variable-sized
PROPSHEETPAGE
structures 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_PUSHLIKE
button 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_SETHILITE
message? - Preventing edit control text from being autoselected in a dialog box
- How do I suppress the
CapsLock
warning on password edit controls? - The early history of the
ES_NUMBER
edit control style - How do I allow negative numbers with the
ES_NUMBER
edit 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_HITTEST
andLVM_INSERTMARKHITTEST
? - Why is there an
LVN_ODSTATECHANGED
notification when there's already a perfectly goodLVN_ITEMCHANGED
notification? - 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_NCCALCSIZE
message - Scrollbars part 11: Towards an even deeper understanding of the
WM_NCCALCSIZE
message - Answers to exercise from Scrollbars Part 11
- Scrollbars part 12: Applying
WM_NCCALCSIZE
to our scrollbar sample - Scrollbars redux: Part 12
- There are two types of scrollbars
- Why was
WHEEL_DELTA
chosen 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_VERTICAL
andCCS_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_RELAYEVENT
and 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_CHECKBOXES
style is quirky, which is a polite way of saying that it is crazy - Beware of the leaked image list when using the
TVS_CHECKBOXES
style - 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
GetKeyState
andGetAsyncKeyState
? - 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/SetMessageExtraInfo
ever used for? - Why is
GetWindowLongPtr
returning a garbage value on 64-bit Windows? TrackMouseEvent
tracks 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
SendMessageTimeout
reaches its timeout? - Why can't I
PostMessage
theWM_COPYDATA
message, but I canSendMessageTimeout
it 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
DispatchMessageA
andDispatchMessageW
are identical, why have both? - Those who do not understand the dialog manager are doomed to reimplement it, badly
Hooking
- What is the
HINSTANCE
passed toSetWindowsHookEx
used for? - How can I get notified when the cursor changes?
- What does the thread parameter to
SetWindowsHookEx
actually mean? - Why does
SetFocus
fail without telling me why?
Specific Messages
Notifications
- What's the difference between the
wParam
of theWM_NOTIFY
message and theidFrom
in theNMHDR
structure. - Restating the obvious about the
WM_COMMAND
message - Restating the obvious about the
WM_NOTIFY
message
Window Construction and Destruction
- What is the difference between
WM_DESTROY
andWM_NCDESTROY
? - How can I determine the reason why my window is closing? (
WM_CLOSE
)
Window Geometry Messages
- Use
WM_WINDOWPOSCHANGED
to react to window state changes - Use
WM_WINDOWPOSCHANGING
to 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_PAINT
message? - 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_SETREDRAW
to speed up adding a lot of elements to a control
Window Focus Messages
WM_KILLFOCUS
is the wrong time to do field validation- The dangers of playing focus games when handling a
WM_KILLFOCUS
message - Why doesn't the
MoveWindow
function generate theWM_GETMINMAXINFO
message?
Keyboard Messages
Mouse Messages
- Why is there no
WM_MOUSEENTER
message? - Why do I get spurious
WM_MOUSEMOVE
messages? - Sure, I can get spurious
WM_MOUSEMOVE
messages, 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_QUERYUISTATE
andWM_UPDATEUISTATE
) - Untangling the confusingly-named
WM_UPDATEUISTATE
andWM_CHANGEUISTATE
messages - Who sends the initial
WM_UPDATEUISTATE
message? - 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_WANTALLKEYS
andDLGC_WANTMESSAGE
have the same value?
Other Window Messages
- The dangers of messing with activation when handling a
WM_ACTIVATE
message - Why does my window get a
WM_ACTIVATE
message when it isn't active? - A timed context menu (
WM_CANCELMODE
) - Pitfalls in handling the
WM_CONTEXTMENU
message (WM_CONTEXTMENU
) WM_NCHITTEST
is 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_NULL
message out of the blue? (WM_NULL
) - Why is there a special
PostQuitMessage
function? (WM_QUIT
) - How does
PostQuitMessage
know which thread to post the quit message to? (WM_QUIT
) - Who is responsible for destroying the font passed in the
WM_SETFONT
message? (WM_SETFONT
) - When I send a
WM_GETFONT
message to a window, why don't I get a font? (WM_GETFONT
) - If my
WM_TIMER
handler takes longer than the timer period, will my queue fill up withWM_TIMER
messages? - Killing a window timer prevents the
WM_TIMER
message 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_ENDSESSION
message, your process can be terminated at any time (WM_ENDSESSION
)
GDI
- Why are
RECT
s endpoint-exclusive? - Can you create an information context for the display?
- What does the
CS_OWNDC
class style do? - What does the
CS_CLASSDC
class style do? - How do you detect "Large Fonts"? (DPI)
- The effect of
SetCursor
lasts only until the nextSetCursor
- 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_INTERNALPAINT
flag? - 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
SaveDC
andRestoreDC
? - How are
BitBlt
raster opcodes calculated? - Notes on
DrawText
and tab stops - Why doesn’t
GetTextExtentPoint
return the correct extent for strings containing tabs? - Why are there trivial functions like
CopyRect
andEqualRect
? - More on trivial functions like
CopyRect
andEqualRect
- 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
- What is the deal with the
SM_CXCURSOR
system 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
CreatePen
and 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
hSection
parameter toCreateDIBSection
for?
LockWindowUpdate()
- What does
LockWindowUpdate
do? - How is
LockWindowUpdate
meant to be used? - With what operations is
LockWindowUpdate
meant to be used? - With what operations is
LockWindowUpdate
not 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
DRAWITEMSTRUCT
structure?
UXTHEME.DLL
BeginBufferedPaint
: It's not just for buffered painting any more- How do
IsThemeActive
,IsAppThemed
, andIsCompositionActive
differ? - 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
ptMaxSize
andptMaxPosition
for 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)
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
CoGetApartmentType
mean? - 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_MEMORY
flag toCoInitializeEx
do? - 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
CoMarshalInterThreadInterfaceInStream
andCoGetInterfaceAndReleaseStream
? - What are the rules for
CoMarshalInterface
andCoUnmarshalInterface
? CoGetInterfaceAndReleaseStream
does 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
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
HRESULT
to a Win32 error code? - Do not overload the
E_NOINTERFACE
error - What does it mean when a call fails with
0x8000001F = RO_E_BLOCKED_CROSS_ASTA_CALL
?
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
... - Why are there four functions for parsing strings into GUIDs, and why are they in three different DLLs?
COM Strings
- Why is there a
BSTR
cache anyway? - Raymond’s complete guide to
HSTRING
semantics - What is the correct way of using the string buffer returned by the
WindowsPreallocateStringBuffer
function?
COM Variants
- What’s the difference between
VARIANT
andVARIANTARG
? - Nasty gotcha:
VarCmp
vsVariantCompare
- Why can’t
VarDateFromStr
parse back a Hungarian date that was generated byVarBstrFromDate
?
IUnknown
- The layout of a COM object
- Under what conditions will the
IUnknown::AddRef
method return 0? - The ways people mess up
IUnknown::QueryInterface
- The ways people mess up
IUnknown::QueryInterface
, episode 2 - The ways people mess up
IUnknown::QueryInterface
, episode 3 - The ways people mess up
IUnknown::QueryInterface
, episode 4 - COM object destructors are very sensitive functions
- Avoiding double-destruction when an object is released
- The COM interface contract rules exist for a reason
- I’d like an
IUnknown
, I know you have many, I’ll take any of them - A very brief introduction to patterns for implementing a COM object that hands out references to itself
- 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
IMoniker
ICallback
IContextMenu
- Why an object cannot be its own enumerator
- How to host an
IContextMenu
, part 1 - Initial foray - How to host an
IContextMenu
, part 2 - Displaying the context menu - How to host an
IContextMenu
, part 3 - Invocation location - How to host an
IContextMenu
, part 4 - Key context - How to host an
IContextMenu
, part 5 - Handling menu messages - How to host an
IContextMenu
, part 6 - Displaying menu help - How to host an
IContextMenu
, part 7 - Invoking the default verb - How to host an
IContextMenu
, part 8 - Optimizing for the default command - How to host an
IContextMenu
, part 9 - Adding custom commands - How to host an
IContextMenu
, part 10 - Composite extensions - groundwork - How to host an
IContextMenu
, part 11 - Composite extensions - composition - Simplifying context menu extensions with
IExecuteCommand
- How do I launch a file as if it were a text file, even though its extension is not
.txt
? - Do not access the disk in your
IContextMenu
handler, no really, don't do it - Sure, we do that: Context menu edition
- Psychic debugging: Why your
IContextMenu::InvokeCommand
doesn't get called even though you returned success fromIContextMenu::QueryContextMenu
- Don’t forget to implement canonical names for verbs in your shell context menu extension
IFileDialog
- The
SetClientGuid
method of the common file and folder dialogs lets you give names to those dialogs, too (multiple contexts for open/save dialogs)
IMultiLanguage
INamespaceWalk
- How can I control which parts of the shell namespace the
INamespaceWalk::Walk
operation will walk into? - How can I cancel the
INamespaceWalk::Walk
operation? - Cancelling the
INamespaceWalk::Walk
operation a little faster
IStream
- The subtleties of
CreateStreamOnHGlobal
, part 1: Introduction and basic usage - The subtleties of
CreateStreamOnHGlobal
, part 2: Suppressing the deletion of an unknownHGLOBAL
- The subtleties of
CreateStreamOnHGlobal
, part 3: Suppressing the deletion of a sharedHGLOBAL
- The subtleties of
CreateStreamOnHGlobal
, part 4: Non-movable memory - A practical use for
GetHGlobalFromStream
when sharing was never your intention
IVirtualDesktopManager
Clipboard
- How ownership of the Windows clipboard is tracked in Win32
- What happens when applications try to copy text by sending
Ctrl+C
- How do I make it so that users can copy static text on a dialog box to the clipboard easily?
- What is the proper handling of
WM_RENDERFORMAT
andWM_RENDERALLFORMATS
? - Copying a file to the clipboard so you can paste it into Explorer or an email message or whatever
- Printing the contents of the clipboard as text to
stdout
- Improving the performance of
CF_HDROP
by providing file attribute information - What’s up with the
CF_SYLK
andCF_DIF
clipboard formats?
Drag and Drop
- What a drag: Dragging text
- What a drag: Dragging a Uniform Resource Locator (URL)
- What a drag: Dragging a Uniform Resource Locator (URL) and text
- What a drag: Dragging a virtual file (
HGLOBAL
edition) - What a drag: Dragging a virtual file (
IStream
edition) - What a drag: Dragging a virtual file (
IStorage
edition) - You can drag multiple virtual objects, you know
- Reading a contract from the other side: Simulating a drop
- Simulating a drop, part two
- What happens if I drag the mouse by exactly the amount specified by
SM_CXDRAG
? - How do I accept files to be opened via
IDropTarget
instead of on the command line? - How do I accept files to be opened via
IDropTarget
instead of on the command line? - bonus content - Using Explorer’s fancy drag/drop effects in your own programs
- Drag/drop effects: The little drop information box
- Why isn’t my shell namespace extension getting every single
DragOver
mouse message?
Enumeration
- Using fibers to simplify enumerators, part 1: When life is easier for the enumerator
- Using fibers to simplify enumerators, part 2: When life is easier for the caller
- Using fibers to simplify enumerators, part 3: Having it both ways
- Using fibers to simplify enumerators, part 4: Filtering
- Using fibers to simplify enumerators, part 5: Composition
Shell
- When does
SHLoadInProc
unload a DLL? - What does
SHGFI_USEFILEATTRIBUTES
mean? - What's the difference between
SHGetMalloc
,SHAlloc
,CoGetMalloc
, andCoTaskMemAlloc
- Querying information from an Explorer window
- Execute a file as if it were a program, even though its extension is not
EXE
- How do I launch a file as if it were a text file, even though its extension is not
.txt
? - What does the
SEE_MASK_UNICODE
flag inShellExecuteEx
actually do? - Simple things you can do with the
ShellExecuteEx
function - What were
ShellExecute
hooks designed for? - Why does
ShellExecute
returnSE_ERR_ACCESSDENIED
for nearly everything? - How do I
ShellExecute
a file, but with a specific program instead of the default program? - What is the difference between
CSIDL_DESKTOP
andCSIDL_DESKTOPDIRECTORY
? SHCIDS_CANONICALONLY
is the moral equivalent in the shell namespace of the Unicode ordinal comparison- Don't forget to double-null-terminate those strings you pass to
SHFileOperation
- Why does
SHFileOperation
have internal error codes for DVD? - Why do non-folders in my shell namespace extension show up in the folder tree view?
SHAutoComplete
giveth, andSHAutoComplete
taketh away- What is the
lpClass
member ofSHELLEXECUTEINFO
used for? - Some known folders cannot be moved, but others can, and you'll just have to accept that
- One possible reason why
ShellExecute
returnsSE_ERR_ACCESSDENIED
andShellExecuteEx
returnsERROR_ACCESS_DENIED
- Why does
SHGetSpecialFolderPath
take such a long time before returning a network error? - How do you obtain the icon for a shortcut without the shortcut overlay? (
SHGetFileInfo()
) - How can I get information about the items in the Recycle Bin?
- Modernizing our simple program that retrieves information about the items in the Recycle Bin
- Invoking commands on items in the Recycle Bin
- How do I perform shell file operations while avoiding shell copy hooks?
- Command line tool to manage Windows 7 Libraries, with source code (
IShellLibrary
) IShellFolder::BindToObject
is a high-traffic method; don't do any heavy lifting- Obtaining the parsing name (and pidl) for a random shell object
- Creating a simple pidl: For the times you care enough to send the very fake
- Creating a simple shell item, just as fake as a simple pidl
- Displaying a property sheet for multiple files
- How do I get a high resolution icon for a file?
- How do I extract an icon at a nonstandard size if
IExtractIcon::Extract
tells me to go jump in a lake? - How do I read the "Double-click to open an item (single-click to select)" setting in Folder Options?
- The wonderful world of shell bind context strings
- Helper functions to make shell bind contexts slightly more manageable
- Customizing item enumeration with
IShellItem
- Customizing item enumeration with
IShellItem
, the old-fashioned way - How do I create an
IShellItemArray
from a bunch of file paths? - How do I invoke a verb on an
IShellItemArray
? - How does a shell namespace extension provide icons for virtual items that track the standard icons set by the user's file associations?
- How do I get the user-customed name of My Computer or Recycle Bin?
- How do I get the user-customized name of a mapped network drive?
- Enumerating all the programs that can open a particular file extension
- Enumerating all the programs that can launch a particular protocol
- How do I register a command on the desktop background context menu? (And how do I remove one I don’t like?)
- How can I get the canonical name for a known folder?
- Peeking inside an
IShellItem
to see what it’s made of - Why does
SHGetKnownFolderPath
returnE_FAIL
for a known folder? - Why does
SHGetKnownFolderPath
fail when impersonating? - Why can’t I use
SHSetKnownFolderPath
to change the location ofFOLDERID_LocalAppData
? - How do I programmatically add a folder to my Documents library?
- Why doesn’t
SHGetFileInfo
give me customized folder icons? - How can I detect that a shell item refers to a virtual folder, or to a file system inside a file?
- Why is there a limit of 15 shell icon overlays?
- The case of the
SHGetFolderPath(CSIDL_COMMON_DOCUMENTS)
that returnedERROR_PATH_NOT_FOUND
- Why is the
HSHELL_WINDOWDESTROYED
notification raised when a window is hidden, even if it hasn’t been destroyed? - Why am I receiving
HCNE_UPDATEDIR
notifications that my code never generates?
Uncategorized COM Stuff
- The macros for declaring and implementing COM interfaces
- An introduction to COM connection points
- Dispatch interfaces as connection point interfaces
- Adjustor thunks
- What is the underlying object behind a COM interface pointer?
- How to turn off the exception handler that COM "helpfully" wraps around your server
- Shortcuts are serializable objects, which means that they can be stored in places other than just a file
- Why does
IFileOperation
skip junctions even though I passedFOFX_NOSKIPJUNCTIONS
? - Nasty gotcha:
STGM_READ | STGM_WRITE
does not grant read/write access - How can I get the list of programs the same way that Programs and Features gets it?
- How do I obtain the computer manufacturer's name via C++? (
IWbemClassObject
) - The stream pointer position in
IDataObject::GetData
andIDataObject::GetDataHere
is significant - The sad implementation history of COM component categories and why it means you have to click twice to see your newly-installed taskbar toolbar
- How do I request that my out-of-process COM server run unelevated?
- How can a desktop app use a Windows Runtime object that infers UI context from its thread? The
IInitializeWithWindow
pattern (IInitializeWithWindow
) - How do I protect myself against a COM call that can hang? I’m already running the server out-of-process.
- What can I do about timer build-up when waiting for COM outbound calls to complete?
- Manipulating the positions of desktop icons
- A reminder about the correct way of accessing and manipulating the position of icons on the desktop
- 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)
- Notes on COM aggregation: Obtaining a pointer to your aggregated partner without introducing a reference cycle
- Notes on COM aggregation: How do you implement tear-offs in an aggregated object?
Memory
- Stupid memory-mapping tricks
- Creating a shared memory block that can grow in size
- Why do I have to pass a valid page protection value to
VirtualAlloc
even if it ignores it? - How can I include/exclude specific memory blocks in user-mode crash dumps?
IsBadXxxPtr
should really be called CrashProgramRandomly (IsBadWritePtr()
et al.)- A closer look at the stack guard page
- The case of the stack overflow exception when the stack is nowhere near overflowing
Input and Output
- Mount points, volumes, and physical drives, oh my!
- What's the difference between an asynchronous
PIPE_WAIT
pipe and aPIPE_NOWAIT
pipe? - Be careful when redirecting both a process's
stdin
andstdout
to pipes, for you can easily deadlock - Looking at the problem at the wrong level: Closing a process's
stdin
ReadDirectoryChangesW
reads directory changes, but what if the directory doesn't change?- How do
FILE_FLAG_SEQUENTIAL_SCAN
andFILE_FLAG_RANDOM_ACCESS
affect how the operating system treats my file? - You can use an
OVERLAPPED
structure with synchronous I/O, too - We're currently using
FILE_FLAG_NO_BUFFERING
andFILE_FLAG_WRITE_THROUGH
, but we would like ourWriteFile
to go even faster - On using
ILE_FLAG_WRITE_THROUGH
andFILE_FLAG_NO_BUFFERING
for memory-mapped files - On the interaction between the
FILE_FLAG_NO_BUFFERING
andFILE_FLAG_WRITE_THROUGH
flags - Why does my synchronous overlapped
ReadFile
returnFALSE
when the end of the file is reached? - Why does
SetFileValidData
fail even though I enabled theSE_MANAGE_VOLUME_NAME
privilege? - Is
GENERIC_ALL
equivalent toGENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE
? CancelIoEx
can cancel I/O on console input, which is kind of niceCancelIoEx
can cancel synchronous I/O, which is kind of nice- Why does
IsPathRelative
returnFALSE
for paths that are drive-relative? - The security check happens at the acquisition of the handle
- Taking a shortcut: You can query properties from a volume, and it will forward to the physical drive
- https://devblogs.microsoft.com/oldnewthing/20201023-00/?p=104395
- How do I disassociate a thread from an I/O completion port?
- Is it okay to call
MapViewOfFile
on the same mapping handle simultaneously from different threads? - What are these dire multithreading consequences that the
GetFullPathName
documentation is trying to warn me about?
Asynchronous Input and Output
- Developing the method for taking advantage of the fact that the
OVERLAPPED
associated with asynchronous I/O is passed by address - Ready... cancel... wait for it! (part 1)
- Ready... cancel... wait for it! (part 2)
- Ready... cancel... wait for it! (part 3)
- If you're waiting for I/O to complete, it helps if you actually have an I/O to begin with
- Why does my asynchronous I/O complete synchronously?
- If an asynchronous I/O completes synchronously, is the
hEvent
in theOVERLAPPED
structure signaled anyway? - You can use an
OVERLAPPED
structure with synchronous I/O, too - Why does my synchronous overlapped
ReadFile
returnFALSE
when the end of the file is reached? - If I issue a second overlapped I/O operation without waiting for the first one to complete, are they still guaranteed to complete in order?
- Why are my file write operations synchronous, even though I opened the file as
FILE_FLAG_OVERLAPPED
? - File-extending writes are not always synchronous, which is entirely within the contract
- Why you might need additional control over the secret event hiding inside the file object
- Why doesn’t my asynchronous read operation complete when I close the handle?
- The mental model for
StartThreadpoolIo
Files and Directories
- The Definitive Guide on Win32 to NT Path Conversion
- How can I tell that a directory is really a recycle bin?
- How can I tell that a directory is weird and should be excluded from the user interface?
- How do I get information about the target of a symbolic link?
- How do I access a file without updating its last-access time?
- How do I show the contents of a directory while respecting the user's preferences for hidden and super-hidden files as well as the user's language preferences?
- You can use a file as a synchronization object, too
- How can I append to a file and know where it got written, even if the file is being updated by multiple processes?
- The
FILE_FLAG_DELETE_ON_CLOSE
flag applies to the handle, also known as the file object, which is not the same as the file - How long do I have to keep the
SECURITY_ATTRIBUTES
andSECURITY_DESCRIPTOR
structures valid after using them to create a file? - How do I create a directory where people can create subdirectories but cannot mess with those created by other users?
- How can I tell whether a file is on a removable drive, a fixed drive, or a remote drive?
- How can I tell whether a file is on an SSD?
- Why does a non-recursive
ReadDirectoryChangesW
still report files created inside subdirectories? - The early history of Windows file attributes, and why there is a gap between System and Directory
- Even if you open a file with GUID, you can still get its name, or at least one of its names (
GetFinalPathNameByHandle()
) - How do I get from a file path to the volume that holds it?
- How do I get from a volume to the physical disk that holds it?
- Renaming a file is a multi-step process, only one of which is changing the name of the file
- How can I recognize file systems that don’t support 64-bit unique file identifiers?
- How can I recognize whether two handles refer to the same underlying file?
ACL
- The
MoveSecurityAttributes
policy affects only how Explorer recalculates ACLs when a file is moved; everybody else is on their own - How to create a folder that inherits its parent’s ACL, and then overrides part of it
Security Permissions, Attributes and Identifiers
- The security check happens at the acquisition of the handle
- What is the default security descriptor?
- How do I convert a SID between binary and string forms?
- An easy way to determine whether you have a particular file permission
- What are the access rights and privileges that control changing ownership of an object?
- How do the names in the file security dialog map to access control masks?
- If you ask for
STANDARD_RIGHTS_REQUIRED
, you may as well ask for the moon - A user's SID can change, so make sure to check the SID history
- Detecting whether a SID is well-known SID
- What's the point of giving my unnamed object proper security attributes since unnamed objects aren't accessible outside the process anyway (or are they?)
- Is a SID with zero subauthorities a valid SID? It depends whom you ask
- What’s the difference between duplicating the handle to a token and duplicating a token?
- I called
AdjustTokenPrivileges
, but I was still told that a necessary privilege was not held - I called
AdjustTokenPrivileges
, but I was still told that a necessary privilege was not held, redux - The history of the
EncodePointer
function for obfuscating pointers - Additional helpful pseudo-handles: The process token, the thread token, and the effective token
- How can I tell whether my process is running as SYSTEM?
Registry
- Beware of non-null-terminated registry strings
- The performance cost of reading a registry key
- So how bad is it that I’m calling
RegOpenKey
instead ofRegOpenKeyEx
? - If I simply want to create a registry key but don’t intend to do anything else with it, what security access mask should I ask for?
- How can I programmatically inspect and manipulate a registry hive file without mounting it?
- Why doesn’t
RegSetKeySecurity
propagate inheritable ACEs, butSetSecurityInfo
does? - Why does
RegNotifyChangeKeyValue
stop notifying once the key is deleted? - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don’t support it? part 1 - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don’t support it? part 2 - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don’t support it? part 3 - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don’t support it? part 4 - How can I emulate the
REG_NOTIFY_THREAD_AGNOSTIC
flag on systems that don’t support it? part 5 - The history of passing a null pointer as the key name to
RegOpenKeyEx
Strings and Locales
TEXT
vs._TEXT
vs._T
, andUNICODE
vs._UNICODE
- The sad history of Unicode
printf
-style format specifiers in Visual C++ - Nasty gotcha:
SetThreadUILanguage
cannot be used to restore the thread UI language - How can
CharUpper
andCharLower
guarantee that the uppercase version of a string is the same length as the lowercase version? (useLCMapStringEx()
in any new code) - Is there a code page that matches ASCII and can round trip arbitrary bytes through Unicode?
- A consequence of being the first to adopt a standard is that you may end up being the only one to adopt it: The sad story of Korean jamo
NT Services
- Calling
ShutdownBlockReasonCreate
from my service doesn't stop the user from shutting down - What does it mean when my attempt to stop a Windows NT service fails with
ERROR_BROKEN_PIPE
? - How can I configure my Windows NT service to autostart when the system gains Internet access?
Uncategorized
- How do I determine the processor's cache line size? (
GetLogicalProcessorInformation()
) - Why are structure sizes checked strictly?
- What's the difference between
CreateMenu
andCreatePopupMenu
? - Why are
HANDLE
return values so inconsistent? - How to retrieve text under the cursor (mouse pointer)
- How to detect programmatically whether you are running on 64-bit Windows
- A timed context menu
- The importance of passing the
WT_EXECUTELONGFUNCTION
flag toQueueUserWorkItem
- If your callback fails, it's your responsibility to set the error code
- The double-click time tells the window manager how good your reflexes are
- The cursor isn't associated with a window or a window class; it's associated with a thread group
- Menu item states are not reliable until they are shown because they aren't needed until then
- How can I display a live screenshot of a piece of another application?
- Converting from a UTC-based
SYSTEMTIME
directly to a local-time-basedSYSTEMTIME
- Programmatically uploading a file to an FTP site
- How can you use both versions 5 and 6 of the common controls within the same module?
- How can I tell if Windows Update is waiting for the system to reboot?
- How do I call
SetTimer
with a timer ID that is guaranteed not to conflict with any other timer ID? - A window can’t have two timers with the same ID, so how do I assign an ID that nobody else is using?
- What does it mean when a display change is temporary?
- How do I obtain the comment for a share?
- How accurate are the various Windows time-querying functions?
- How can I detect whether the user is logging off?
- Why are timer IDs and dialog control IDs 64-bit values on 64-bit Windows? Did you really expect people to create more than 4 billion timers or dialog controls?
- If you suppress GDI+ background thread, then you are expected to pump messages yourself
- If one program blocks shutdown, then all programs block shutdown (
WM_QUERYENDSESSION
,WM_ENDSESSION
) - When I ask the
GetIpAddrTable
function to sort the results, how are they sorted? - How can I detect that the system is no longer showing a UAC prompt? (
EVENT_SYSTEM_DESKTOPSWITCH
) - How can I get the number of processors in the system, when there are more than 64?
- Why are some system functions exported as stubs instead as forwarders?
- How can I check whether the user has disconnected from the session?
- Why does
PF_VIRT_FIRMWARE_ENABLED
return false even when virtualization is enabled in the firmware? - How can I convert between IANA time zones and Windows registry-based time zones?
- The focus rectangle says, “I’m not orange. I’m just drawn that way.”
- Why does the precise point at which I get a stack overflow exception change from run to run? (structured exception handling aka SEH)
- How do I programmatically reposition monitors in a multiple-monitor system? (
ChangeDisplaySettingsEx()
) - How do I upgrade a 32-bit tick count to a 64-bit one?
- The error code you get might not be the one you want
- How can I find out which processor architectures are supported via emulation by the current system?
- How can I detect whether the system has a keyboard attached? On the
GetRawInputDeviceList
function - Filtering out fake keyboards from the
GetRawInputDeviceList
function - How expensive is
PssCaptureSnapshot
? How fast is it? How much memory does it consume?