The Old New Thing
Practical development throughout the evolution of Windows.
Latest posts
How can I prevent the user from changing the widths of ListView columns in version 5 of the common controls?, part 2
Preventing the resize cursor from appearing.
How can I prevent the user from changing the widths of ListView columns in version 5 of the common controls?
Deny changes to the width.
Super Bowl LX creates an opportunity for symphonic friendly wagering
Betting classical music.
How can I prevent the user from changing the widths of ListView columns?
You can ask the header to be non-resizing.
Some small stories about the giant satellite dish antenna that was behind Microsoft Building 11
A little trivia.
Studying compiler error messages closely: Input file paths
Are you even compiling the correct file?
Why not store the SAFEARRAY reference count as a hidden allocation next to the SAFEARRAY?
The case of "Bring your own <CODE>SAFEARRAY</CODE>."
How can I retain access to the data in a SAFEARRAY after my method returns?
Find a way to take ownership.
Why did I lose the data even though I called SafeArrayAddRef?
You have to use the original pointer, but even that won't be good enough.
A digression on the design and implementation of SafeArrayAddRef and extending APIs in general
The concerns when adding a feature to an existing API.
What’s the difference between SafeArrayAccessData and SafeArrayAddRef?
Two ways of preserving the data.
C++ has scope_exit for running code at scope exit. C# says “We have scope_exit at home.”
You can wrap it in an <CODE>IDisposable</CODE>.
A simple helper function for attaching a progress handler to a Windows Runtime IAsyncActionWithProgress or IAsyncOperationWithProgress
It doesn't do much, but it saves typing.
On the proper usage of a custom Win32 dialog class
You are replacing the window procedure, not the dialog procedure.
Microspeak: On fire, putting out fires
Dealing with emergencies.
What was the secret sauce that allows for a faster restart of Windows 95 if you hold the shift key?
An old flag from 16-bit Windows.
How can I get the tab index number from a dialog box control?
The tab index number is an authoring concept, not a runtime concept.
When programs assume that the system will never change, episode 4: Stealing strings
The strings are an implementation detail.
Clipping the focus item when looking for its on-screen location, part 3
Finding <I>all</I> the clipping parents.
Clipping the focus item when looking for its on-screen location, part 2
Finding the correct clipping parent.
Clipping the focus item when looking for its on-screen location
Preventing the cursor from pointing to nothing.
Using Active Accessibility to find out where the focus item is
Looking at child objects.
Using Active Accessibility to find out where the Windows caret is
It's old and rather simple, but we like simple.
How can I find out where the Windows caret is?
You'll have go to a larger scope.
Swapping two blocks of memory that reside inside a larger block, in constant memory, refinement
Could do with a little less rotating.
How can you swap two non-adjacent blocks of memory using only forward iterators?
Applying the rotation trick to our new problem.
How can you swap two adjacent blocks of memory using only forward iterators?
A different algorithm, employing a different kind of cleverness.
Swapping two blocks of memory that reside inside a larger block, in constant memory
A variation on the constant-memory rotation.
2025 year-end link clearance
Another year gets relegated to history.
Understanding and mitigating a stack overflow in our task sequencer
The recurring problem of synchronous resumption.
Additional notes on color-keyed overlays as a way of doing smooth video rendering
Choosing the color-key and other brief discussions.
The Gävle Goat (Gävlebocken) succumbs in 2025 to a new menace
You could blow me over.
How can I detect that the system is running low on memory? Or that my job is running low on memory?
You can register for a memory notification.
Why are we worried about memory access semantics? Full barriers should be enough for anybody
You have to find new ways of going faster.
Reading the fine print, episode 4: Holiday promotions
Checking those validity dates.
Why is the last letter of my string not making it to the clipboard?
The struggle for null termination.
Why does my Ctrl+M accelerator key activate when I press the Enter key?
Understanding the difference between keys and characters for accelerators.
When irate product support customers demand to speak to Bill Gates
So transfer them to his office, or so it seems.
All the other cool languages have try…finally. C++ says “We have try…finally at home.”
The destructor serves as the "finally".
A shortcut gives me a weird path for a program shortcut that doesn’t point to the executable, so what is it?
It's a placeholder because the shortcut is to an MSI application.
Concluding thoughts on our deep dive into Windows clipboard text conversion
Stick to Unicode and you'll be fine.
Deducing the consequences of Windows clipboard text formats on UTF-8
Working out the implications.
Why is the Windows clipboard taking the scenic route when converting from CF_TEXT to CF_OEMTEXT ?
Something is forcing it down an alternate path.
Misunderstanding what the Cricket Celebration Bowl is
Apparently, not a bowl of crickets.
The Windows clipboard automatic text conversion algorithm is path-dependent
When the journey is not half of the fun.
Resolving an ambiguity in the Windows clipboard automated text conversion table
Who goes first?
Studying the various locale mismatch scenarios in Windows clipboard text format synthesis
If they don't match, then the 8-bit strings are basically broken already.
How does Windows synthesize the CF_LOCALE clipboard format?
Getting it from a place that might have been obvious in the past, but maybe not today.
How does Windows synthesize CF_UNICODETEXT from CF_TEXT and vice versa?
Let's ask the locale.
How does Windows synthesize CF_OEMTEXT from CF_TEXT and vice versa?
Starting with the easy case, or at least it looks easy.
How can my process read its own standard output?
You'll have to trick yourself before anybody notices, which may not be possible.
How can I read the standard output of an already-running process?
You can't. You'll have to do it before the process starts.
How do I check whether the user has permission to create files in a directory?
Request the directory security attributes that correspond to your proposed operation.
Microspeak: Big rocks
The large obstacles.
How do I get my edit control text to be autoselected when I choose it to be the default focus in my dialog?
Remembering some old APIs.
How can I have a Win32 drop-down combo box with a read-only edit control?
You can ask for its handle and mark it read-only.
Message-only windows are for messaging, not as a convenient victim for hosting UI
If you want to host UI, use a real window (possibly hidden).
At what point in the Windows development cycle is it too late to change the text of a translatable string?
The translation team sets the deadline.
The apocryphal origins of the Hot Dog Stand color scheme
Challenge accepted.
Why does XAML break down when I have an element that is half a billion pixels tall?
You've far exceeded the design goals and have even exceeded the expressive ability of a float.
Maybe somebody can explain to me how weak references solve the ODR problem
I don't see it.
In the commit-on-demand pattern, what happens if an access violation straddles multiple pages?
The access violation exceptions will continue until commit improves.
Is WriteProcessMemory faster than shared memory for transferring data between two processes?
Shared memory is the copy-free solution.
Microspeak: Little-r
Harkening back to a very old mail program.
How can I detect that Windows is running in S-Mode, redux
Doing it on hard mode.
I can use WM_COPYDATA to send a block of data to another window, but how does it send data back?
They can send it back with their own <CODE>WM_<WBR>COPYDATA</CODE> message, or they can put it in an agreed-upon shared location.
Could we use CTAD to simplify the use of WRL’s Callback function?
Not directly, but maybe indirectly.
Non-recursively deleting a binary tree in constant space: Rotating the tree
Preserving in-order while linearizing.
Behind the scenes on how Windows 95 application compatibility patched broken programs
Replacing bytes with the greatest of care.
How did Windows 3.1 distinguish two different programs that happened to share the same executable name?
The trouble with disambiguation.
Non-recursively deleting a binary tree in constant space: Restructuring the tree
Changing the tree structure to make it easier to delete.
Non-recursively deleting a binary tree in constant space: Synthesizing the parent pointer
Making one as you go.
Non-recursively deleting a binary tree in constant space: Traversal with parent pointers
First assume that you have a parent pointer.
The Microsoft SoftCard for the Apple II: Getting two processors to share the same memory
Reportedly Microsoft's first hardware product.
Why does SHFormatDateTime take an unaligned FILETIME?
Designed for its original use case.
Microspeak: turn into a pumpkin
To disappear, such as for the year-end holidays.
Trying to build a XAML tree in code throws a “No installed components were detected” exception
An unfortunate error code collision, but the explanatory text leads the way.
What to do when you have a crash in the runtime control flow guard check
You don't have to understand it, but you should be able to extract data from it.
How did the Windows 95 user interface code get brought to the Windows NT code base?
Ported bit by bit.
Dubious security vulnerability: Denial of service by loading a very large file
I mean, it's what you asked it to do.
The early history of the Windows Runtime PropertyValue and why there is a PropertyType.Inspectable that is never used
It used to be there because PropertyValue started out as the fundamental variant type before shifting focus to being the fundamental boxed type.
Windows Runtime design principle: Properties can be set in any order
If all you're doing is setting properties, you can do it any way you like.
What makes cheap_steady_clock faster than std::chrono::high_resolution_clock ?
It's quite a bit faster, though maybe you don't care.
Microspeak: The hockey stick on wheels
You're always a year away.
What about the icons in pifmgr.dll?
Just for fun.
Using RAII to remedy a defect where not all code paths performed required exit actions, follow-up
If the callback requires copyability.
Using RAII to remedy a defect where not all code paths performed required exit actions
Passing the obligation onward.
Why can you increment a reference count with relaxed semantics, but you have to decrement with release semantics?
It's more important to clean up when you leave.
I remember taking a screen shot of a video, and when I opened it in Paint, the video was playing in it! What witchcraft is this?
You copied the green screen.
API design principle: Don’t tempt people to divide by zero
Remove it from the equation.
The self-assignment principle for Windows Runtime properties: Don’t change behavior based on whether a property has been written to
The fact that a property has been set does not by itself trigger functionality.
The self-assignment principle for Windows Runtime properties applies to default values
The default value must be legal.
Windows Runtime API design principles around read-write properties: Idempotence and self-assignment
Setting it to the value it already has is not a crime.
Remembering the end of support for VRML in Internet Explorer
No one left standing.
Code comments should apply to the state of the system at the point the comment “executes”
Putting them in the flow.
Can we get weak functions for static linking? The Visual C++ compiler says “We have weak functions at home”
It's already there, just under a different paradigm.
The problem with inferring from a function call operator is that there may be more than one
<CODE>auto</CODE> parameters make this easy to write, particularly for lambdas.
How do I convert a FILETIME to a C++ clock like std::system_clock or winrt::clock?
The <CODE>winrt::clock</CODE> has a conversion for you.
Microspeak: Convicted
False backformation.
How can I enumerate the overflow icons in the Notification Area without showing them?
If they aren't shown, then they aren't automatable, so there's no requirement that they exist in the UI automation tree.
Why didn’t Windows 95 setup install a miniature Windows 95 so that it could be written as a 32-bit program?
Getting to the GUI quickly, and rebooting only once.
Samples note: Use comments to describe what code does, not what you wish the code would do
Comments explain the code. They are not substitutes for the code.
Why is Windows still tinkering with critical sections?
The critical section may be an old dog, but it's still learning new tricks.
Another lesson learned from the Windows 98 on-stage USB blue screen
Test before using.
Why was Windows 3.0’s WinHelp called an online help system when it ran offline?
It was online in a different sense.
Learning to read C++ compiler errors: Not a legal base class
What would make it an illegal base class?
Can I close a duplicate handle while I’m waiting on the original?
That's fine, since you're not closing the handle that you're waiting on.
How can I get my shell thumbnail extractors to run in the same process?
Adding another level of indirection.
Translating the STATUS_STACK_BUFFER_OVERRUN status code into customer-ready text
Reducing the level of alarm.
Why is the name of the Microsoft Wireless Notebook Presenter Mouse 8000 hard-coded into the Bluetooth drivers?
Is it some sort of favoritism?
How can I convert a third party in-process server so it runs in the COM surrogate?
You can put your own object in the surrogate first.
Why can’t std::apply figure out which overload I intend to use? Only one of then will work!
The overload resolution happens before the compiler knows what it's going to be used for.
The documentation says that CompanyName version information is required, but my program seems to work without it, so how required is it?
It's more of a "Very strongly recommended" than a "Required".
A suggestion to people who assign nicknames to meeting rooms
Lean into the pattern. Don't try to cross it up.
Why didn’t Windows 95 simply special-case the laptops that locked up when it executed the HLT instruction?
The catastrophic risk of bricking a computer.
The case of the crash on a null pointer even though we checked it for null
Understanding what you're checking.
How can I write a C++/WinRT IAsyncOperation<T> where T is not a Windows Runtime type?, part 2
Safer smuggling.
How can I write a C++/WinRT IAsyncOperation<T> where T is not a Windows Runtime type?, part 1
It's not representable in the Windows Runtime, but you can smuggle it.
Dubious security vulnerability: Remembering passwords for recently-opened ZIP files
If it didn't remember them, you wouldn't like it.
Thoughts on creating a tracking pointer class, part 16: Second attempt to use a list
We can splice nodes to move them between lists.
Thoughts on creating a tracking pointer class, part 15: A custom shared pointer
Simplifying it for out limited use case.
Thoughts on creating a tracking pointer class, part 14: Nonthrowing moves with the shared tracking pointer
Moving the exception somewhere else.
Thoughts on creating a tracking pointer class, part 13: Restoring the strong exception guarantee
Don't commit to anything until you know you can finish the job.
Thoughts on creating a tracking pointer class, part 12: A shared tracking pointer
Sharing a single tracking pointer among all instances.
Thoughts on creating a tracking pointer class, part 11: Repairing assignment
Restoring things that were automatically deleted.
Thoughts on creating a tracking pointer class, part 10: Proper conversion
Making sure you cannot remove qualifiers.
Thoughts on creating a tracking pointer class, part 9: Conversion
Making a read-only tracking pointer from a read-write tracking pointer.
Thoughts on creating a tracking pointer class, part 8: Tracking const objects
Making tracking pointers to const objects.
Thoughts on creating a tracking pointer class, part 7: Non-modifying trackers, second try
Another attempt to make tracking pointers to objects that you can't modify.
Thoughts on creating a tracking pointer class, part 6: Non-modifying trackers
Making tracking pointers to objects that you can't modify.
Thoughts on creating a tracking pointer class, part 5: Copying our tracking pointer
How to copy from a const tracking pointer.
Thoughts on creating a tracking pointer class, part 4: Using a circular doubly linked list
Building our own circular doubly-linked list.
Thoughts on creating a tracking pointer class, part 3: Using a std::vector
Tracking your trackers with a vector.
Thoughts on creating a tracking pointer class, part 2: Using a std::list
Tracking your trackers with a <CODE>std::list</CODE>.
Thoughts on creating a tracking pointer class, part 1: Concept art
Following an object as it moves.
Under what conditions could a ReadFile or WriteFile fail to transfer all of the bytes, and how do I detect that?
If there is not enough data to read, or not room to write.
How can I detect that Windows is running in S-Mode?
Check the code integrity policy.
How do I disable pieces of the property sheet for a service in the Services MMC snap-in?
There's no secret setting. It's all based on access control.
Why are Windows semiannual updates named H1 and H2?
To address an unconscious bias.
How can I read more than 4GB of data from a file in a single call to ReadFile?
You can't, but you can try to fake it.
Two related questions about keeping track of PIDs of IPC clients
Since you're doing IPC, you may as well let IPC do the work for you.
A consequence of the weird wReserved value at the start of the DECIMAL structure
It overwrites things by accident.
In C++/WinRT, how can I await multiple coroutines and capture the results?, part 0
If you don't really care about what happens if something goes wrong.
Why is there a window with no name blocking Windows shutdown?
They never expected you to see it.
API design note: Don’t make up multiple names for the same thing
It may be obvious to you, but that's because you wrote it.
How can I confirm in the Windows debugger that I’m looking at a COMDAT-folded function?
Ask for all the names for an address.
How can I wait until a named object (say a mutex) is created?
You can't, but maybe you can wait for something else.
Exploring possible solutions to the inconsistency in how Windows searches case-insensitively for named resources
Maintaining compatibility while addressing flaws.
Being more adamant about reporting that C++/WinRT was unable to resume execution on a dispatcher thread
Better versions in a different box.
What happens if C++/WinRT is unable to resume execution on a dispatcher thread?
What you get out of the box.
The case of the invalid instruction exception on an instruction that should never have executed
I don't recall ever asking you to do that.
If the Window Runtime PropertyValue is for boxing non-inspectables, why is there a PropertyValue.CreateInspectable?
For completeness, but not for functionality.
The Fundamental Failure-Mode Theorem: Systems lie about their proper functioning
It doesn't say what it does on the tin.
Perhaps not a recommended usage for an emergency power outlet
Maybe that's not a critical system.
There is a std::chrono::high_resolution_clock , but no low_resolution_clock
For when you care only enough to be roughly on time.
Detecting and reporting all unhandled C++ exceptions as well as all unhandled structured exceptions
Closing another exit point.
Our first attempt to detect and report all unhandled C++ exceptions as well as all unhandled structured exceptions
Identifying and classifying the exit points.
When I install an unhandled structured exception filter, why doesn’t std::terminate get called?
You're using the same hook that the compiler uses to call <CODE>std::<WBR>terminate</CODE>.
A walkthrough of the original Microsoft Building 3
Don't get lost on your walk down memory lane.
Dubious security vulnerability: If I perform this complex series of manual steps, I can crash a program I am running
What security boundary did you cross?
Why doesn’t LVIF_INDENT work without an image list?
Its original client had an image list.
German language cheat sheet: On changing quantities
How much there is, and how is it changing.
If the FormatMessage function fails, and I requested that it allocate a buffer, do I have to free the buffer?
There was no buffer returned, so there's nothing to free anyway.
Unintended yet somehow entirely expected consequences of marking a COM interface as local
If it's local-only, then it can't be remote.
The sizzle reel that says things that nobody understands
Failing to understand your audience.
2025 mid-year link clearance
Halfway there.
Embracing the power of the empty set in API design: Requesting zero items
It's okay to ask for nothing. You get nothing.
Why do I get errors or warnings about some weird symbol called ?main@@YAHP$01E$AAV?$Array@PE$AAVString@Platform…, part 3
Forcing <CODE>main</CODE> to be found in the place we want.
Why do I get errors about some weird symbol called ?main@@YAHP$01E$AAV?$Array@PE$AAVString@Platform…, part 2
Figuring out why C++/CX makes a difference.
Your information has been permanently deleted, for small values of permanently
Is it really gone?
Why do I get errors about some weird symbol called ?main@@YAHP$01E$AAV?$Array@PE$AAVString@Platform…, part 1
Welcome to the world of C++/CX. Is "welcome" the right word?
Abusing copyright strings to trick software into thinking it’s running on your competitor’s PC
I did technically cross my fingers.
The MIDL compiler still has trouble with double greater-than signs, sadly
Many have tried.
The case of the invalid handle error when a handle is closed while a thread is waiting on it
You are theorizing one race but experiencing another.
Learning to read C++ compiler errors: Ambiguous symbol errors after including a header file
Finding out why multiple entities with the same name are visible.
You have to tell Get- and SetSecurityInfo the object type, you can’t make it guess
It needs to know which provider to give it to.
Funding the Egghead store shopping spree took a little extra legwork
Just ask the boss.
Writing a helper class for generating a particular category of C callback wrappers around C++ methods
Another exercise in C++ template programming.
Thread pool threads are like preschool: Leave things the way you found them
Your mother always told you to clean up behind yourself.
Why does Windows even have Interlocked functions when we have std::atomic?
Well, you have to start somewhere.
Removing the MAX_PATH restriction on paths applies only to paths
The individual file names still retain their existing limits.
Application compatibility for Windows 95 crashed a cash register
Exceeding all reasonable maximums.
Dubious security vulnerability: Tricking a program into running non-elevated
You can do anything, but still within the limits of your authority.
Why does C++ think my class is copy-constructible when it can’t be copy-constructed?
You said that you had a copy constructor, even though it can't be compiled.
Why do some Windows functions fail if I pass an unaligned Unicode string?
Well, if you don't align it, then you've already broken the rules.
Riffing on a typo in the name of the opera Turandot
On the dot.
How can I programmatically find the network path by which a folder has been shared?
There is no direct query. You'll have to infer it.
The symbolism of the magnifying glass is not universal
Just making things bigger?
Stating the obvious about debugging an invalid parameter error when freeing memory
Writing it down for posterity.
Using an oracle to see where your code is producing the wrong output
If there is a reference implementation, then use it as a check.
The case of creating new instances when you wanted to use the same one
C++ language backward compatibility makes legal what you had hoped wasn't.
How do I convert a WIC bitmap back to a GDI HBITMAP?
You can copy the bits into a DIB section.
What was origin of the code name Redpill for Windows 8 feature lockout?
Pretty obvious, actually.
Why does EnumProcessModules report no modules on a process that was created suspended?
There are no modules yet because you didn't give them a chance to load.
How can I detect if one of my helper processes is launching child processes?
You can ask a job object to keep track for you.
How can I create a window the size of the screen without it being treated as a fullscreen window?
You can declare that you aren't rude.
Silly parlor tricks: Promoting a 32-bit value to a 64-bit value when you don’t care about garbage in the upper bits
Inline assembly that doesn't do anything.
Why does Windows report my processor speed twice, with slightly different values?
One is calculated. The other is self-promotion.
Secret passages on Microsoft main campus, episode 3
Another covered passage between buildings.
What’s with the weird wReserved value at the start of the DECIMAL structure?
It's where the discriminant goes when the <CODE>DECIMAL</CODE> is put "inside" a <CODE>VARIANT</CODE>.
How do I force RunOnce commands to run in a specific order?
Run them in the desired order yourself.
If I mark my thread pool callback as long-running, does it still count toward the thread pool thread limit?
Yes, because it's still in the thread pool.
What is the developer set-up for developing Windows for multiple processor architectures?
You usually just pick one and count on your friends for the others.
Dubious security vulnerability: A program does not run correctly if you run it the wrong way, redux
Trying to make the system run the program automatically.
How can I wait for Clipboard History to recognize a clipboard change before I change it again?
Listen for the change event.
Why doesn’t Clipboard History capture rapid changes to clipboard contents?
Clipboard history operates asynchronously, so you are changing it before it can respond to the changes.
What were the MS-DOS programs that the moricons.dll icons were intended for?
Tallying them up.
What were the MS-DOS programs that Windows used the progman.exe stock icons for?
Mostly generic-looking icons.
What were the intended uses of those icons in moricons.dll?
Icons for old MS-DOS apps.
Using type aliasing to avoid the ODR problem with conditional compilation, part 2
Ensuring that you pick a side.
Using C++ type aliasing to avoid the ODR problem with conditional compilation, part 1
Still one definition, but two types.
Why does Windows have trouble finding my Win32 resource if it contains an accented character?
Disagreements over the fine print.
Protecting Windows users from Janet Jackson’s Rhythm Nation
Granting an exception to a system policy.
Why did Windows 7, for a few months, log on slower if you have a solid color background?
It's waiting for Godot and eventually gives up.
If we can have std::atomic<std::shared_ptr>, why not std::atomic<com_ptr>?
Controlling the reference count.
When I define a window class with no default cursor, what is the explanation for the cursors that appear in my client area?
You said you'd take care of it, but you didn't.
What resource ID should I give my application’s main icon?
Applying what we know about how Explorer finds the "first" icon in a file.
Microspeak: top of mind
Things I'm thinking about.
The ongoing story of seconds on the taskbar
The cost of ticking.
The case of the feature flag that didn’t stay on long enough, part 2
Leaving everything the way you found it.
The case of the feature flag that didn’t stay on long enough, part 1
Understanding scope and order of destruction.
Using the classical model for linking to provide unit test overrides
Overriding a LIB with an OBJ for fun and profit.
There was a lot of imagined dropping tablets in swimming pools
The archetypical example of needing a replacement computer.
Dubious security vulnerability: Once I have tricked the user into running a malicious shortcut, I can install malware
Yes, that's sort of the point.
The case of the UI thread that hung in a kernel call
I did tell you not to do that.
Function overloading is more flexible (and more convenient) than template function specialization
You can change more things in an overload.
Why can’t I use SEC_LARGE_PAGES with a file-based file mapping?
No paging, no crying.
The Goldilocks zone of software stability
Not too new, not too old.
On priority inversion in the use of a spinlock to ensure atomic access to a shared_ptr
Priority inversion may be rare, but correctness doesn't care about rarity.
Adding delays to our task sequencer, part 3
Waiting more cheaply.
Adding delays to our task sequencer, part 2
Waiting the right amount of time.
Adding delays to our task sequencer, part 1
Not so fast there.
The return of Building 7
Pranksters lose one of their longtime inside jokes.
If one program blocks shutdown, then all programs block shutdown, revisited
No take-backs.
The 2025/2026 Seattle Symphony subscription season at a glance
The pocket reference guide for 2025/2026.
Fixing exception safety in our task_sequencer
Exception safety, the forgotten requirement.
On launching a dialog when a specific combo box item is selected
Changing selections is not a good time to launch a dialog box.
Why does INVALID_HANDLE_VALUE cast through a LONG_PTR first?
LONG_PTR first? To ensure that the proper sign extension happens.
We’ll fly you to Atlanta, Texas, and getting to your hotel in Atlanta, Georgia is your problem
Reading the fine print.
A note on the USB-to-PS/2 mouse adapter that came with Microsoft mouse devices
It's a purely mechanical adapter that relies on smarts in the mouse itself.
On how different Windows ABIs choose how to pass 32-bit values in 64-bit registers
Surveying the options and looking for commonalities.
The case of the critical section that let multiple threads enter a block of code
It had one job.
What could cause a memory corruption bug to disappear in safe mode?
A simplified execution environment means fewer things that you can stumble over.
You can’t simulate keyboard input with PostMessage, revisited
If it didn't go through the input system, it only looks like input as much as the app allows itself to be fooled.
Why didn’t Windows 95 setup use a miniature version of Windows 95 as its fallback GUI?
Avoiding an interim GUI environment.
Dubious security vulnerability: A program does not run correctly if you run it the wrong way
So what did you expect?
The case of COM failing to pump messages in a single-threaded COM apartment
A customer encountered a hang caused by COM not pumping messages while waiting for a cross-thread operation to complete. They were using the class for serializing asynchronous operations on a UI thread they created to handle accessibility callbacks. The hang stack looked like this: We see that we have a UI thread (notice the at the bottom of the stack), yet COM decided to block without pumping messages ( instead of (). Is this a bug in the task sequencer? Let's look at the stack more closely. A message arrived via , and that then queued a task into the task sequencer. The saw that the task sequencer had...
Making sure that a DLL loads only from your application directory
You can ask for it as an option, but think about what you're actually protecting against.
What are the thread safety requirements of HSTRING and BSTR?
They do not have thread affinity.
What an insightful observation, you get to wear “the hat”
Maybe not so insightful.
How do I destroy an ABI pointer that I extracted from a C++/WinRT object?
You can clean it up the ABI way, whatever that is.
To some people, time zones are just a fancy way of sounding important, episode 2
Words have meaning.
How can I choose a different C++ constructor at runtime?
Make somebody else do it, and then use copy elision.
I tried to subscribe to a C++/WinRT event, but my callback was never called
Check how you registered your event handler.
Microspeak: Respin
Spin it up again, baby.
Lexically scoped functions accessing parent locals: The display
Using a well-known location instead of copying frame pointers.
C++/WinRT implementation inheritance: Notes on winrt::implements, part 8
Comparing the options.
C++/WinRT implementation inheritance: Notes on winrt::implements, part 7
Inheritance without involving <CODE>winrt::implements</CODE> at all.
C++/WinRT implementation inheritance: Notes on winrt::implements, part 6
Using CRTP to delegate the method.
C++/WinRT implementation inheritance: Notes on winrt::implements, part 5
When the base class isn't self-contained.
C++/WinRT implementation inheritance: Notes on winrt::implements, part 4
Simple inheritance of a self-contained <CODE>implements</CODE>.
C++/WinRT implementation inheritance: Notes on winrt::implements, part 3
Discovering the legal inheritance structures for <CODE>winrt::<WBR>implements</CODE>.
C++/WinRT implementation inheritance: Notes on winrt::implements, part 2
Untangling <CODE>unwrap_<WBR>implements_t</CODE>.
C++/WinRT implementation inheritance: Notes on winrt::implements, part 1
A closer look at the parameters to the <CODE>implements</CODE> template.
Your statement is now available, just two hidden flyouts and five clicks away
Beware of the leopard.
API design note: Beware of adding an “Other” enum value
What are you going to do when you add a new kind?
Investigating an argument-dependent lookup issue and working around it
Picking apart the language specification.
A sample implementation of the weak reference pattern for COM callbacks
A forwarder through a weak reference.
Async-Async revisited: What about cancellation?
Even the cancellation is async.
Did the Windows 95 setup team forget that MS-DOS can do graphics?
Oh look what you just made there.
How does Explorer find the “first” icon in a file
It enumerates them and takes the first one, so this is really a question about enumeration.
Using alternate locales to get more interesting case mapping than the C
Looking for something better.
The default C locale is not a very interesting one
It barely understands anything.
On exactly when XAML bindings are evaluated if an element is not yet loaded
It depends on which abstraction you prefer.
The original name for Flexible Single Master Operations in Active Directory
Not that kind of F-word.
On trying to log an exception as it leaves your scope
You can't watch it from an object on the outside.
Creating a generic insertion iterator, part 2
Satisfying the iterator requirements, perhaps with a little cheating.
Creating a generic insertion iterator, part 1
We provide the boilerplate; you provide the smarts.
How do I create an inserter iterator that does unhinted insertion into an associative container like std::map?
Curiously missing from the standard library.
My electric toothbrush was acting up, so I tried to reboot it
It didn't help.
A pattern for obtaining a single value while holding a lock
The immediately-invoked lambda that returns a value.
A brief and incomplete comparison of memory corruption detection tools
A short overview, definitely incomplete.
Memory corruption from outside the process looks like space aliens
The write isn't visible to your process, just the effect of the write.
Be mindful of temporal terms in documents: What is the reference point in time?
What is your implied point in time for the reference?
Why is there a bulge on my bicycle tire when I inflate it?
Get the order of operations right.
Why doesn’t the Windows blue screen of death prominently identify the company that created the driver that crashed?
Because the driver that crashed may not be the one at fault.
Reminder: When a C++ object fails to construct, the destructor does not run
If you need to run after a failed construction, you have to put it in a base class or member variable.
The case of the crash when trying to erase an element from a std::set
Another kind of fiasco.
In a C++ class template specialization, how can I call the unspecialized version of a method?
You can't talk about things that might exist, so instead talk about things that do.
How does GetUserDefaultGeoName choose between ISO 3166-1 and UN M.49 codes?
Clarifying the behavior.
Microspeak: The walk-on topic
Just walk on in with your topic.
A simplified overview of ways to add or update elements in a std::map
And using it to find missing opportunities.
Why does inadvertently passing a std::string instead of a char const* to a variadic function crash on x86-32 but not x86-64?
Looking at the calling convention and the small string optimization.
Inside STL: Waiting for a std::atomic<std::shared_ptr<T>> to change, part 2
Digging into the libstdc++ implementation.
Inside STL: Waiting for a std::atomic<std::shared_ptr<T>> to change, part 1
Waiting on a single pointer, but checking for two.
Gesellschaft zur Stärkung der Verben: The German Society for the Irregularization of Verbs
Stand strong and proud.
Emergency power resets on Lenovo, HP, Dell, and Acer laptops
Looking for the magic button.
How can I tell whether a change to a control was due to the user or due to my program?
You know when it was done by your program because you did it.
Forcing an ERROR_KEY_DELETED error when trying to open HKEY_CURRENT_USER\Software
Just an exercise to show that it can be done, even though it's highly unlikely to occur in practice.
Could I be getting ERROR_KEY_DELETED for HKEY_CURRENT_USER\Software when the user logs off?
Probably not, but there are some edge cases.
How is it possible to get ERROR_KEY_DELETED when I’m creating a key?
The key that got deleted is not the one you are trying to create.
2024 year-end link clearance
The cycle completes.
Making sure the Microsoft Visual C++ compiler chooses the right source encoding
Making sure the file and settings are set correctly.
How various git diff viewers represent file encoding changes in pull requests
The invisible UTF-8 BOM, and sometimes invisible encoding changes.
In C++, failure to meet the requirements does not always mean that you fail if you don’t meet the requirements
Combining SFINAE/requires, standard layout, and overload resolution.
Why are Win32 resources strings bundled at all? And why bundles of 16?
Balancing multiple performance factors.
How can I check if two GUIDs are equal when they are provided as strings?
A customer asked if there was a helper function in the system that accepted two strings and reported whether the s they represent are equal. This is a tricky question, because you first have to decide what "represent" means. There are many ways of representing a as a string. It could be just 32 case-insensitive hexadecimal digits. Or maybe there are internal hyphens to separate the groups. And the whole thing might be enclosed in braces or parentheses. External and interior whitespace might be allowed. Trailing garbage might be accepted (and ignored). And then there's the special format {0x00000000,0x0000,0x00...
A design flaw in the Windows 3D Pipes screen saver pointed out by a customer
Time-wasting.
A common proposed solution to certain categories of IFNDR: Getting the linker to verify identical functions
You could do it, but it could cramp your style.
How do I register a file type for a scripting language so that users get a warning when they run an untrusted script?
Use the FTA_AlwaysUnsafe edit flag.
Inside STL: The atomic shared_ptr
There's a lock hiding inside the pointer.
Is there a way to split the git history of a file or combine the histories of two files without a merge commit?
Studying how git recovers history.
Microspeak terms that didn’t take hold: airspace, synthetics, and AOI
Sometimes they don't stick.
Why do we have header files <pshpackN.h> and <poppack.h> instead of just issuing the pragma directly?
Because the pragma may not work everywhere.
Converting to a derived class from the future: How to cast from a base class to an incomplete derived class?
Deferring the definition until the class is complete.
API naming principles for conditional operations: On, When, and If
Describing when a condition is tested.
What is the CONTINUE_IF_FAILED equivalent of RETURN_IF_FAILED?
Be careful how you write it, or better: Don't write it at all.
It rather involved being on the other side of this airtight hatchway: Disabling anti-malware scanning
If you have already infiltrated the process, then you can disable things from the inside.
Learning to read C++ compiler errors: Failing to create a shared_ptr
Understanding what you asked the compiler to do, and why it couldn't comply.
Learning to read C++ compiler errors: Nonsensical errors from a function declaration
Look closely at what the error message is complaining about.
Won’t waiting for multiple threads one at a time introduce a severe performance issue?
It depends on how long you plan on waiting.
Why does my DLL reference count go up by one every time I create and exit a thread?
If you use a wrapper, you need to follow the wrapper's rules.
Tricks from product support: We’re not smart enough to debug the problem, can you help us?
It's not you, it's me.
News flash: Desire for loud cars correlates with psychopathy and sadism
More research into loud vehicles.
An analogy about register preservation rules in calling conventions
And tying it back to unwind codes.
Assessing the attack complexity of a race condition security vulnerability
It's not just how small the race window is, but how easy it is to hit the window.
Why does my program successfully take foreground only when running under the debugger?
That's a special exception to the normal foreground rules.
Checking whether a URI refers to a Web site root
Let somebody else do the parsing.
Microspeak: Real estate and Airspace
Space on the screen and negotiating control over it.
How can I know when a window has processed a message that I posted to it?
Best would be to have it tell you.
In C++, how can I make a default parameter be the this pointer of the caller?, revisited
Expanding on the previous pattern.
How can I detect which menu my item was invoked from?
Just give them all different IDs. But this might itself by an XY problem.
How do I determine whether Explorer is showing or hiding file extensions?
You can ask, but maybe you're asking the wrong question.
A wrinkle in how Windows 95 setup bootstrapped its initial GUI step
Getting access to the common controls that don't exist until Windows 95.
The operations for reading and writing single elements for C++ standard library maps
Breaking down the options.
How do I put a non-copyable, non-movable, non-constructible object into a std::optional?
Taking advantage of the conversion operator.
Solving the puzzle of trying to put an object into a std::optional
How do I set a value? Let me count the ways.
The puzzle of trying to put an object into a std::optional
The C++ standard library template type has one of two states. It could be empty (not contain anything), or it could contain a . Suppose you start with an empty . How do you put a into it? One of my colleagues tried to do it in what seemed to be the most natural way: Use the assignment operator. Unfortunately, the assignment failed to compile: I asked for the rest of the error message, because the details will explain what the compiler tried to do (and why it couldn't). It's long, but we'll walk through it. The compiler is showing its work. It's showing you all the possible overloaded assignment opera...
Why did Windows 95 setup use three operating systems?
Simplifying the problem to an earlier problem.
Debugger breakpoints are usually implemented by patching the in-memory copy of the code
The code in memory may not match what the debugger shows you if the debugger is itself is doing the changing.
The case of a program that crashed on its first instruction
Didn't even make it out of the gate.
Why do I observe reads from a memory-mapped file when writing large blocks?
The CPU doesn't see the entire write at once.
How do I declare an operator overload for my Windows Runtime class?
That's not something expressible in the Windows Runtime.
What’s the difference between Display size and Screen size in the Windows 95 display control panel?
No meaningful difference, though others have created a difference.
On the limits of time travel in the face of undefined behavior in C
C imposes some constraints, but the principle is mostly still there.
On locale-aware substring matching, either case-sensitive or case-insensitive
It's surprisingly complicated, but fortunately, somebody has done it for you.
What has case distinction but is neither uppercase nor lowercase?
It has one foot in each world but belongs to neither.
I have enabled “take ownership” permission, but I still cannot obtain write access
Taking ownership is only one part of gaining write access.
Reverse-engineering what a “short” section is
The long and short of it all.
How useful is the hint passed to the std::unordered_… collections?
Only a little, or sometimes not at all.
How can I explicitly specialize a templated C++ constructor, follow-up notes
You can use a maker function, but that doesn't let you escape the problem.
It rather involved being on the other side of the airtight hatchway: Defeating ASLR after you’ve gained RCE via ROP
If you defeat ASLR, then you can defeat ASLR.
How do I create a Windows Runtime IRandomAccessStream around a bunch of bytes or a classic COM IStream?
Another wrapper function.
Did Windows 95 shrink the default font size of windowed MS-DOS apps?
The effect was that it shrunk, but only sometimes.
Why does adding WS_MINIMIZEBOX change how my window behaves when the user presses Win+D?
It minimizes your window if it can.
Evaluating tail call elimination in the face of return address protection, part 2
Rewriting the activation frame.
Evaluating tail call elimination in the face of return address protection, part 1
Reusing the activation frame.
Effects of classic return address tricks on hardware-assisted return address protection
Return address manipulations that are possibly even more impermissible than they already were.
A quick introduction to return address protection technologies
Detecting attempts to manipulate the return address.
On naming things: The tension between naming something for what it is, what it does, or how it is used
You are guaranteed to make someone upset.
How can I explicitly specialize a templated C++ constructor?
Looking for a C++ tag type for representing another type.
A correction to the awaitable lock for C++ PPL tasks
Over-scoped lock.
If threads are created without a message queue, why can I post to them immediately upon creation?
Check who is doing the posting.
Microspeak: Run to ground
Come to a resolution.
A popular but wrong way to convert a string to uppercase or lowercase
Converting character by character isn't good enough any more.
How does the linker decide whether to call WinMain or wWinMain?
If you don't tell it, it will try to figure it out.
How can I detect whether the user is running as an elevated administrator (as opposed to a natural administrator)?
You can ask for the elevation type.
A function for creating an absolute security descriptor from a self-relative one
Just wrap it up.
Misunderstanding the “Prevent access to registry editing tools” policy
It prevents access to the tools, but not to the registry itself.
Pulling a single item from a C++ parameter pack by its index, remarks
Why such a complicated way to pull the type from the pack?
The case of the crash when destructing a std::map
Who is corrupting the map?
If you’re going to specify the LVS_SORTASCENDING or LVS_SORTDESCENDING style, you had better be telling the truth
Because the listview control uses it to optimize searching.
Another example of the Windows Runtime interop pattern: Using the UserConsentVerifier from a Win32 program
Following the standard pattern.
The UserConsentVerifier confirms that the user is there, but it doesn’t protect any data
Is that really you?
Going beyond the empty set: Embracing the power of other empty things
Just because there's nothing in it doesn't mean it's not valid.
How can I check that all the changes in a git branch have been cherry-picked or rebased into its upstream branch?
You can pretend to merge it and see if anything happens.
My window has the WS_EX_NOACTIVATE extended style, but it got activated anyway
Well, at least it wasn't activated by a click.
More on the mysterious [default_interface] attribute in Windows Runtime classes
Forcing you to make a choice.
It rather involved being on the other side of this airtight hatchway: Posting completions to somebody else’s I/O completion port
If you have gained access to it, then that was the problem.
Some notes on Win32 carets
Assorted notes and musings.
The case of the fail-fast crashes coming from the power management system
Understanding why it decided to fail fast.
How can I tell whether two programs will share drive letter mappings?
You can compare the authentication IDs.
The case of the string being copied from a mysterious pointer to invalid memory, revisited
Reflections on an older topic.
Does the Resource Compiler have a separate preprocessor or doesn’t it?
It did, but now it doesn't.
GitHub trick to find the commit that deleted a file
Ask for the history of the file.
The case of the image that came out horribly slanted: Negative stride
It's all topsy-turvy.
The case of the image that came out horribly slanted: Taking the pitch into account
Getting the pieces to line up.
The case of the image that came out horribly slanted: Diagnosis
Imperfect pitch.
Why did Windows 95 use blue screen error messages instead of hard error messages?
You may not able to get there from here.
The CoInitializeSecurity function demands an absolute security descriptor
Even though you usually have a self-relative one in hand.
In the Windows kernel, what is a LUID, and what makes it loo-ey?
It's a locally-unique ID, for a specific definition of "local".
How is the Windows.Foundation.Uri.Domain property different from Host?
It's an educated guess.
On the strange status of wchar_t in classic MIDL
From the era before <CODE>wchar_t</CODE> was a standard type.
The Microsoft/IBM joint development was built on mutual respect, wait, is respect the right word?
Maybe it's some other word.
Thoughts on finding the essential elements of a set
Another binary search, but searching a different way.
What if I need to wait for more than MAXIMUM_WAIT_OBJECTS threads?
Studying your options, and the consequences of breaking things up.
The role of the activation factory in the Windows Runtime
The activation factory represents the class itself.
What does ERROR_KEY_DELETED mean?
You now have a handle to a key that doesn't exist, and there's nothing you can do with it.
Another tribute to Microsoft history hiding in Building 41
Logo touches.
Constructing nodes of a hand-made linked list, how hard can it be?
Trying to force copy elision.
The case of the missing ordinal 380
Untangling the error message and developing a theory.
Instead of putting a hash in the Portable Executable timestamp field, why not create a separate field for the hash?
That would defeat the purpose.
Temporarily dropping a lock: The anti-lock pattern
It's not to prevent locking, but rather to counteract a lock.
A look back at one of the (many) projects code-named Highlander
The showdown that almost repeated.
Embracing the power of the empty set in API design (and applying this principle to selectors and filters)
You got plenty of nothing.
What does it even mean to Close a Windows Runtime asynchronous operation or action?
That's the end of the road.
Why do I get E_ACCESSDENIED when trying to access my brokered Windows Runtime object?COM is double-checking the trust level.
COM is double-checking the trust level.
How do I know when the user has finished interacting with the AccountsSettingsPane?
You can use the version that runs an asynchronous operation.
It rather involved being on the other side of the airtight hatchway: Disabling a security feature as an administrator
At least they don't beat around the bush.
What are the dire consequences of registering a RunOnce command from my RunOnce command?
The circle of life, or a perpetual motion machine.
The difference between undefined behavior and ill-formed C++ programs
They are two kinds of undefined-ness, one for runtime and one for compile-time.
What’s the difference between DataPackageView.GetUriAsync and DataPackageView.GetWebLinkAsync ?
Just improving on an ambiguous name.
How to compress out interior padding in a std::pair and why you don’t want to
Context-sensitive layout means you get a different structure each time you use it.
There is no mystery over who wrote the Blue Screen of Death, despite what some may want you to believe
No real contradictions in anybody's story.
Why don’t Windows Imaging Component pixel format GUIDs continue their nice pattern?
Patterns are predictable, which is not always a good thing.
What can I do if IMlangConvertCharset is unable to convert from code page 28591 directly to UTF-8?
You can do the conversion in two steps using things you already have.
In my Visual Studio project, I set my Conformance mode to permissive, but it’s still not permissive
Digging into what the compiler sees.
API naming principle: If there is no direct object, then the direct object is the source object
If you don't know what it operates on or produces, then it operates on or produces itself.
Unquoted service paths: The new frontier in script kiddie security vulnerability reports
Usually not exploitable, but the script kiddies don't know that.
Organizing the five creation dispositions of the CreateFile function
Six possibilities, but only five useful ones.
Creating an already-completed asynchronous activity in C++/WinRT, part 9
Cheating the delegates.
Creating an already-completed asynchronous activity in C++/WinRT, part 8
Generalizing the pattern.
Creating an already-completed asynchronous activity in C++/WinRT, part 7
Implementing the contract directly.
Creating an already-completed asynchronous activity in C++/WinRT, part 6
Let the conversion do the talking.
Creating an already-completed asynchronous activity in C++/WinRT, part 5
Trying to fail more correctly.
Creating an already-completed asynchronous activity in C++/WinRT, part 4
Failing is easy. Failing correctly is hard.
Creating an already-completed asynchronous activity in C++/WinRT, part 3
Generalizing to the four kinds of Windows Runtime asynchronous activities.
Creating an already-completed asynchronous activity in C++/WinRT, part 2
Making our function a coroutine.
Creating an already-completed asynchonous activity in C++/WinRT, part 1
The simplest version.
What’s the point of std::monostate ? You can’t do anything with it!
Not doing anything with it is exactly the point.
How do I produce a Windows Runtime asynchronous activity from C++/WinRT?
Somebody that deals with them natively.
How do I produce a Windows Runtime asynchronous activity from C#?
The AsyncInfo helper class converts Tasks to Windows Runtime asynchronous activities.
How do I produce a Windows Runtime asynchronous activity from C++/CX?
The Parallel Patterns Library has special support for C++/CX.
The history of Alt+number sequences, and why Alt+9731 sometimes gives you a heart and sometimes a snowman
Code pages and custom keyboard handling.
If I register the same shell extension as both a context menu extension and a drag/drop extension, how do I know which one the system is using?
Who forced you to register the same shell extension for both?
2024 mid-year link clearance
Emptying out the junk drawer.
Writing a remove_all_pointers type trait, part 2
Factoring out the type resolution to after the dangerous part.
Writing a remove_all_pointers type trait, part 1
Delaying the expansion to avoid infinite recursion.
Is there a built-in way in C++/WinRT to get the string name for a Windows Runtime enum?
No, and maybe you don't want to.
Microspeak: Fun fork
A place to party.
Finding a specific value in a sequence of integers that changes by at most 1
It's basically a discrete version of the intermediate value theorem.
The Windows Runtime winrt::hstring and the C++ std::wstring are inter-assignable
Just assign them over, no cermony necessary.
How to convert between different types of counted-string string types
Looking for constructors that take a character count.
On the sadness of treating counted strings as null-terminated strings
You're throwing away perfectly good data, there.
The time smart quotes prevented the entire Office division from committing code
Breaking your tools with your tools.
How can I view the list of symbols available in a library?
A tool hiding inside another tool.
Lock-free reference-counting a TLS slot using atomics, part 3
Keeping track of two things at once.
Lock-free reference-counting a TLS slot using atomics, part 2
Getting it is easy. Getting rid of it is hard.
Lock-free reference-counting a TLS slot using atomics, part 1
First, we do it with locks.
The origin story of the Windows 3D Pipes screen saver
Looking for a place to show off.
How do I get the name of a SID, and what does it mean when the conversion fails?
Most places will do it for you, or at least try.
What’s the deal with std::type_identity?
When you want to use a type without participating in type deduction.
Can INI files be Unicode? Yes, they can, but it has to be your idea
It'll only be Unicode if it's already Unicode.
How 16-bit Windows cached INI files for performance
Taking advantage of co-operative multitasking.
Why does GlobalLock max out at 255 locks?
Because that's how many bits were available for reporting the lock count.
More on harmful overuse of std::move
Could we expand copy elision to cover the harmful cases?
A graphical depiction of the steps in building a C++ executable, with XAML and packaging
Fleshing out the diagram.
A graphical depiction of the steps in building a C++ executable, enhanced for classic Win32
Adding in Microsoft-specific tools.
A graphical depiction of the steps in building a C++ executable, basics
A high-level overview.
How can I force a DLL to register itself if it won’t respond to regsvr32?
You can't force something that isn't there.
Is there any difference between StringFromIID and StringFromCLSID?
Not really.
Setting the contents of a Windows Runtime Vector from C++/WinRT in one call
The one-stop shop for updating a Windows Runtime Vector.
Creating a prepopulated Windows Runtime Vector from C++/WinRT without going through an explicit std::vector
Creating the vector inline.
If you have to create a Windows Runtime Vector from C++/WinRT, do it as late as possible
Stay with the <CODE>std::vector</CODE> until you really need the Window Runtime Vector.
A blurry photo of the legendary USB Cart of Death
And some details about that infamous on-stage bluescreen.
If you know what interface you want, just pass it directly to CoCreateInstance
Avoiding a second round trip.
Why can’t I find the injected name of a templated class’s templated base class?
The compiler needs help finding it because it's not findable at the time the template is parsed.
Pulling a single item from a C++ parameter pack by its index
Combining a few tools to make a new tool.
Building the most efficient device selector query that selects no devices
Looking for the most efficient way of rejecting everything.
The confidential coffee maker was not the only source of shenanigans at the IBM Boca office
The culture (and weather) clash continues.
Before you try to change something, make sure you can change nothing
Nobody touch anything.
An informal comparison of the three major implementations of std::string
Pros and cons.
Asking for a DispatcherQueue from a GUI thread you created
Grafting a DispatcherQueue onto an existing thread.
Awaiting a set of handles with a timeout, part 7: Just doing it one at a time
A simpler version with its own quirks.
Awaiting a set of handles with a timeout, part 6: Capturing the handles efficiently
SFINAE'ing the case of a random-access(ish) iterator.
Awaiting a set of handles with a timeout, part 5: Generalizing the awaiter
Fitting into existing patterns.
Awaiting a set of handles with a timeout, part 4: Building our own awaiter
To stop relying on unspecified behavior.
Awaiting a set of handles with a timeout, part 3: Going beyond two
Generalizing what we learned last time.
Awaiting a set of handles with a timeout, part 2: Continuing with two
Giving it another try.
Awaiting a set of handles with a timeout, part 1: Starting with two
Let's see by seeing if we can do it with just two.
Awaiting a set of handles in C++/WinRT
It's easier thank you think.
Adding state to the update notification pattern, part 8
Comparing the two algorithms.
Adding state to the update notification pattern, part 7
Going free-threaded.
Adding state to the update notification pattern, part 6
Using a change counter with coalescing.
Adding state to the update notification pattern, part 5
Using a change counter.
Adding state to the update notification pattern, part 4
What if the UI thread isn't there to save you?
Adding state to the update notification pattern, part 3
Abandoning the background work if we know that it is pointless.
Adding state to the update notification pattern, part 2
First attempt to try to fix the race condition.
Adding state to the update notification pattern, part 1
Where each notification depends on some state information.
In search of the Ballmer Peak, and other results from SIGBOVIK 2024
Continuing studies in silliness.
Dubious security vulnerability: Program allows its output to be exfiltrated
Once the output is generated, the program can't control where it goes.
What were the tax consequences of letting Windows 95 team members keep a piece of software as long as they tested it?
It basically falls under the <I>de minimis</I> rule.
The case of the string being copied from a mysterious pointer to invalid memory
Using AppVerifier to deduce the heap allocation history.
Why do STANDARD_RIGHTS_READ , STANDARD_RIGHTS_WRITE , and STANDARD_RIGHTS_EXECUTE have the same values?
Don't they mean different things?
How can I find out which process has locked me out of the clipboard?
You can ask for the clipboard opener.
If I enumerate all the processes and add up all the GetGuiResources, why doesn’t it match the GR_GLOBAL value?
There are some things that aren't charged to processes.
How does the classic Win32 ListView handle incremental searching?
Combining prefix search with repeated search, to accommodate multiple styles.
The case of the exception that a catch (…) didn’t catch
Reconstructing a false history.
It rather involved being on the other side of this airtight hatchway: System corruption caused by an administrator
If your goal was to corrupt the system, you sure are doing it the hard way.
Windows debugger trick: Breaking when a specific debugger message is printed
A different kind of conditional breakpoint.
The history of computing, as told by the hallways of Microsoft Building 41
A walk through history, in the form of wall textures.
Subroutine calls in the ancient world, before computers had stacks or heaps
A lot of computing got done even before we had stacks and heaps.
How can I tell C++ that I want to discard a nodiscard value?
A variety of tricks, with different degrees of readability and legality.
I called CreateEnvironmentBlock with a process’s token, but I didn’t get that process’s environment
That's not what the <CODE>CreateEnvironmentBlock</CODE> function does.
Some choices for encrypting data so that it can be decrypted only by the same user or computer
There's your classic, and there's some newfangled stuff.
Dubious security vulnerability: Manual operations can cause a program to hang
You did this to yourself.
Why isn’t C++ using my default parameter to deduce a template type?
Trying to have it both ways.
Why does my thread get a broken string as its initial parameter?
It got converted too late.
Using the DisplayInformation class from a desktop Win32 application, part 2
Completing the prerequisites.
Using the DisplayInformation class from a desktop Win32 application, part 1
A little interop music.
How well does C++/WinRT com_ptr support class template argument deduction (CTAD)?
It doesn't even try, and probably doesn't want you to do it.
How well does wil com_ptr support class template argument deduction (CTAD)?
Falling into a hole in the C++ language, not filled in until C++20.
How well does WRL ComPtr support class template argument deduction (CTAD)?
It tries too hard and accidentally breaks CTAD.
How well does ATL CComPtr support class template argument deduction (CTAD)?
It actually works right out of the box.
How well does MFC IPTR/CIP support class template argument deduction (CTAD)?
Not very well, thanks to requiring the interface ID to be specified explicitly.
How well does _com_ptr_t support class template argument deduction (CTAD)?
Not very well, thanks to storing the pointer and IID pair in a helper type.
Class template argument deduction (CTAD) and C++ COM wrappers: Initial explorations
How well do these libraries support a feature that likely didn't exist at the time they were written?
The 2024/2025 Seattle Symphony subscription season at a glance
The pocket reference guide for 2024/2025.
How can I force a copy of a C++ value?
Forcing a copy with a minimum of typing.
In C++/WinRT, you shouldn’t destroy an object while you’re co_awaiting it
A generalization of the ground rules of programming.
How do I make an expression non-movable? What’s the opposite of std::move?
You can turn it into a const thing so it's no longer movable, in a conventional sense.
In domain\user syntax, you can often use the period as an abbreviation for “this computer”
A bit of a typing saver, particularly with complex machine names.
Is shadowing a member variable from a base class a bad thing? Maybe, but maybe not.
It depends on the order in which things occurred.
C++/WinRT performance trap: Switching to Windows Runtime too soon
Stay in the devirtualized world until you are forced to leave.
If a parameter isn’t used, what should I pass?
It doesn't matter what you pass, but if you have to ask, then just pass zero.
On the whole idea of giving away a reference to yourself at destruction
Hey, at least it's possible.
Mitigating attacks based on knowing the length of a Windows Hello PIN
Balancing convenience against security, and how you can tune the knobs toward more security.
A C# LINQ one-liner to check if exactly one of a set of conditions is met
Maybe not the most efficient, but it's easy to write.
Gotcha: Be careful how you shut down your dispatcher queues
The dispatcher queue thread isn't useful after it has shut down, so don't try anything.
Gotcha: Don’t forget to shut down your dispatcher queues
Keep that dispatcher queue controller around, or you'll never be able to clean up.
Once your object reaches final_release, you are committed to destructing it (eventually)
Don't try to resurrect it.
Microspeak: Closing out, duping out
Making work items no longer appear on a query.
Why can’t I trigger a manual blue screen crash by injecting the magic key sequence?
It has to come from the physical keyboard, because that's the code that detects the magic key sequence.
If you’re just going to sit there doing nothing, at least do nothing correctly
How to be inert.
Registered command lines are just command lines, not a programming language
If you want a programming language, you know where to find one.
Functions that return the size of a required buffer generally return upper bounds, not tight bounds
An over-estimate is better than an under-estimate.
It rather involved being on the other side of this airtight hatchway: Attacking a domain administrator from the local administrator
If you pwn the machine, then you pwn everyone on the machine.
How can I get the Windows Runtime HttpClient to display a basic authentication prompt?
You need to give it some help finding the right window.
On the virtues of the trailing comma
A more uniform appearance comes with its own benefits beyond aesthetics.
How do I suppress the error box that appears when a LoadLibrary fails?
They don't appear often, but they do appear occasionally.
Why doesn’t my program get fancy drag/drop effects in high contrast mode with CLSID_DragDropHelper ?
You have to upgrade your manifest.
On using milliseconds as a measure of network latency
There's a limit to how much technology can improve.
How can I close a thread pool and cancel all work that had been queued to it?
You can put them in a group.
The case of the invalid parameter error from MeasureOverride
Chasing it back to its origin.
Using virtual memory placeholders to allocate contiguous address space for multiple purposes
Can you hold this for a second?
How can I add an environment variable to a process launched via ShellExecuteEx or IContextMenu?
Hooking into the way the Windows shell launches processes.
Smoothing over the differences (and defects) in the various implementations of IMemoryBuffer
Stick to the part that nobody messes up.
A comparison of various implementations of the Windows Runtime IMemoryBuffer
Every unhappy class is unhappy in its own way.
How can I expose a pre-existing block of memory as a Windows Runtime object without copying the data?
Assembling all the pieces.
How can I give away a COM reference just before my object destructs?
You have to do it before committing to destruction.
The dangerous implementations of the IMemoryBufferReference.Closed event
Mistakenly handing out COM references that don't work.
The useless IMemoryBufferReference.Closed event
It tells you that you have already lost.
Accessing a block of memory represented by a Windows Runtime IMemoryBuffer
Through the currency known as an IMemoryBufferReference.
The case of the fail-fast trying to log a caught exception
What is being thrown and why can't we log it?
Implementing two-phase initialization with ATL
ATL looks like it supports two-phase initialization, but it doesn't.
Getting a strong reference from the this pointer too soon
Giving out strong references to an object before you can guarantee that it will work.
What is a hard error, and what makes it harder than an easy error?
A throwback to the early days of 16-bit Windows.
C++/WinRT gotcha: Not all exceptions derive from hresult_error
There are also C++ standard exceptions, particularly <CODE>std::bad_alloc</CODE>.
In C++/WinRT, how can I await multiple coroutines and capture the results?, part 3
Dealing with awaitables that return <CODE>void</CODE>, and questioning our life choices.
In C++/WinRT, how can I await multiple coroutines and capture the results?, part 2
Wrapping the results and returning them in a tuple.
In C++/WinRT, how can I await multiple coroutines and capture the results?, part 1
Using a custom awaiter to suppress the <CODE>GetResults()</CODE>.
After I accidentally denied access to everyone, how do I get access back?
Congratulations, you locked your keys in the car.
How do I prevent my C++/WinRT implementation class from participating in COM aggregation?
Looking for a clue.
The case of the vector with an impossibly large size
Play threading games, win threading prizes.
How can I specify icons for my app to use on the Start menu in high contrast mode?
Put them in your manifest.
Why doesn’t my code compile when I change a shared_ptr<T>(p) to an equivalent make_shared<T>(p)?
It depends on who is doing the parameter conversion.
It rather involved being on the other side of this airtight hatchway: Attacking another program by modifying its memory
If you assume the existence of a vulnerability, you can use that vulnerability to attack something.
How do I prevent my ATL class from participating in COM aggregation? DECLARE_NOT_AGGREGATABLE didn’t work
That marker applies only to creation via the class factory.
2023 year-end link clearance
Ringing out another year.
How to allocate address space with a custom alignment or in a custom address region
Some new powers to guide the allocation.
On calling AfxConnectionAdvise with bAddRef set to FALSE
Playing fast and loose, and eventually you get burnt.
What does it mean when the compiler says that it can’t convert something to itself?
Why is it even thinking about a conversion?
Don’t keep state in your XAML item templates; put the state in the items
Beware of temporary alliances.
That time the Word team sent presents to the children of WordPerfect’s executive vice president
No, it wasn't creepy.
If I don’t have any items, what error should my IFolderView::Items method return?
It shouldn't return an error at all.
How do I get access to the wParam and lParam of the WM_QUERYENDSESSION method from my MFC message handler?
Don't be afraid to see how the macros are built.
It rather involved being on the other side of this airtight hatchway: Spoofing another program
You already had the power to do it yourself.
Microspeak: Locked and loaded
Armed and ready, with the suggestion that no further changes will be needed (or accepted).
In 2023, the Gävle Goat faces a new threat to its survival
It's bock.
If the RegisterClass function takes ownership of the custom background brush, why is it leaking?
It takes ownership only on success.
How do I specify an optional string parameter to a Windows Runtime method?
Strings are sort of reference but sort of values.
How do I specify an optional parameter to a Windows Runtime method?
There is no way to express explicit optionality, but there are implicit ways.
How can I work around the absence of default parameters in the Windows Runtime?
You can fake it with overloads.
What happens if I define one environment variable in terms of the value of another environment variable?
Only certain types of dependencies are supported.
The mysterious second parameter to the x86 ENTER instruction
For an ABI that probably nobody uses.
A simpler version of the task sequencer that doesn’t promise fairness
Just let a kernel object control the access.
In C++, how can I make a default parameter be the this pointer of the caller?
Again, you can't, but you can fake it.
In C++, how can I make a member function default parameter depend on this?
You can't, but you can fake it.
What was the code name for 64-bit Windows?
Sundown, which was a hidden jab at the competition.
What is a static chain pointer in the context of calling convention ABI?
Buried in the System V Application Binary Interface.
Why does the Windows Portable Executable (PE) format have both an import section and input directory?
They seem to be the same thing. Do we need both?
Why does the Windows Portable Executable (PE) format have separate tables for import names and import addresses?, part 2
Keeping read-only data separate from read-write data.
Why does the Windows Portable Executable (PE) format have separate tables for import names and import addresses?, part 1
Even though their lifetimes don't overlap, you sometimes need to go back in time.
A reported vulnerability about getting paid apps for free is really about paying for free apps
Try shopping around.
In Windows 3.1 and Windows 95, what is a “grabber”?
It grabbed your MS-DOS screen and put it into a window.
On harmful overuse of std::move
Initial excitement leads to overuse.
On the need to keep most event sources alive if you want them to raise events
You can't receive a notification from something that doesn't exist.
How can I convert a Windows Runtime SoftwareBitmap to a WIC bitmap?
The reverse of <CODE>ISoftwareBitmapNativeFactory::<WBR>CreateFromWICBitmap</CODE>.
Microspeak revisited: Line of sight
A fancy way of saying unimpeded network connectivity.
If you’re going to crash on an unhandled exception, you may as well do it sooner rather than later
Avoiding the problem discovered by the case of the invalid argument exception from a method that takes no arguments.
The theory behind the IHttpFilter interface
Layering features on top of each other.
What happened to the custom exception description I threw from a C++/WinRT IAsyncAction?
The description is just a courtesy and is not part of the API contract.
Why does calling a coroutine allocate a lot of stack space even though the coroutine frame is on the heap?
Heap elision optimization kicks in, and doesn't kick out.
Starting on the other side of this airtight hatchway: Running a program that leaks memory
There are a lot of things you can do to consume memory.
What is the difference between UuidToString, StringFromCLSID, StringFromIID, and StringFromGUID2?
Different ways of stringizing a GUID.
The case of the invalid argument exception from a method that takes no arguments
Where did the invalid argument come from?
A clarification on the multithreading constraints of the EncryptMessage function
Reading a sentence in the context of the whole paragraph.
How can I get information about media playing on the system, and optionally control their playback?
Going to the global system media transport controls world.
“Stop sharing this folder” is not the same as “Never share this folder”
It stops sharing the folder, but that doesn't prevent you from starting it again.
Why doesn’t reduction by modulo work for floating point values?
Working out why it works for integers and seeing what goes wrong.
Why does unsafe multithreaded use of an std::unordered_map crash more often than unsafe multithreaded use of a std::map ?
It's all in the implementation details.
How come my custom exception message is lost when it is thrown from a IAsyncAction^?
Things that survive in the C++ world and things that are lost when you cross the ABI.
More notes on use of the DS_CONTROL style
Styles that have to go in, and styles that have to come out. (And styles that you can choose.)
What is the thread reaper?
Should you fear the thread reaper?
What are the dire consequences of not removing all the properties that were set via SetProp?
Not so much any more, but it could be a sign that you forgot something.
How to support a COM interface conditionally in WRL
Customizing the QueryInterface and GetIids methods.
How to support a COM interface conditionally in C++/WinRT
Prevent <CODE>winrt::implements</CODE> from responding to it or reporting it.
The format of icon resources, revisited
Filling in some gaps.
Why is there a hash of a weak password in the Windows cryptographic libraries?
They're part of an internal self-test.
How do I add a non-copyable, non-movable object to a std::map or std::unordered_map?
Fancy emplacement.
On the failed unrealized promise of RegOverridePredefKey
An early attempt to sandbox the registry for a process.
What’s the difference between setting a page’s protection to PAGE_NOACCESS and freeing it?
Nobody can access it, but it's still there.
How can I check if I’m on a DispatcherQueue’s thread if I can’t call HasThreadAccess?
Looking at the tools you have available.
Microspeak: The As-Appropriate (AA) interviewer
So, how are things going so far?
API design principle: Reading a property or adding an event handler should not alter observable behavior
Don't punish people for looking.
On detecting improper use of std::enable_shared_from_this
Playing around with the standard library.
I created an overloaded operator for my C++/WinRT class, but it’s not working
Take a closer look at what you are overloading.
Why does IFileDialog still show non-filesystem folders when I pass FOS_FORCEFILESYSTEM ?
Because you need to pass through them to get there.
It rather required being on the other side of this airtight hatchway: Knowing the domain administrator password
If you give away the password, well, that's sort of on you.
Is there any performance advantage to marking a page read-only if I had no intention of writing to it anyway?
The CPU already figured it out.
A very belated improvement to the filtering of the Browse for Folder dialog so it shows only drive letters
The case of the very short UNC.
How can I get WideCharToMultiByte to convert strings encoded in UTF-16BE?
You first have to get it into a format the WideCharToMultiByte accepts.
On the confusing names for the Windows service SID types
Too much abbreviation.
A complaint about Links the Cat, the Office assistant
Do all cats do that?
How do I manually update a remote tracking branch, say, to undo a fetch?
Updating refs to point to whatever you like.
Template meta-programming: Avoiding saying a type before it is complete
Deferring use until after the class is defined.
C++/WinRT gotcha: get_strong() will produce a broken strong reference if destruction has already begun
A strong reference to nothing.
The dangers of releasing the last strong reference from within its own callback
Deadlocking with yourself.
Why is kernel32.dll running in user mode and not kernel mode, like its name implies?
It's just a name, and it comes from the days before user-mode/kernel-mode separation.
GetQueueStatus and the queue state
There's stuff going on that's hiding behind the innocuous-looking name.
When I try to call an exported function, the target crashes when it tries to call any Windows function
Using what you know about how functions are imported to construct a theory that matches the evidence.
How does Explorer calculate the “Date” of a file?
Mapping the generic concept to specific file types.
Why does my C++/WinRT project get unresolved externals for constructors?
You forgot to include the namespace header file, didn't you.
Why did the 16-bit _lopen and _lcreat function return -1 on failure instead of 0?
Trying to look like somebody else.
When looking to free up disk space, don’t forget your symbol file caches
They go all over the place.
How can I prevent myself from using a parameter after I’ve extracted all value from it?
You can shadow it with something useless.
I accidentally performed an operation on INVALID_HANDLE_VALUE , and it worked: What just happened?
Coincidentally valid, but not what you think.
How do I perform a case-insensitive comparison of two strings in the Deseret script?
It sort of depends on why you're comparing them.
The odd cadence of narrative engineering design documents
Following the rubric off a cliff.
Any sufficiently advanced uninstaller is indistinguishable from malware
The common pattern of trying to delete yourself.
On transferring or copying ABI pointers between smart pointers
Keep track of who owns the reference.
A freestanding JavaScript function that uses this is easily mistaken for a constructor
Because that's what constructors look like.
Detecting whether a tree-like data structure contains a cycle
Combining two things we already know.
When documentation cautions that something may not happen, that suggests that it normally does happen
Reading between the lines.
Just for fun: What happens when you shift a register by more than the register size?
A comparative study of processor architectures.
How do I find out more about the fail-fast exception that occurs when an exception in a PPL task goes unobserved?
Digging into the internals.
Diagnosing a crash when trying to call ReadFile via language interop
Checking the signatures and inferring what could have gone wrong.
How can I programmatically obtain the value of the “Make text bigger” slider?
The text scale factor property.
The popularity of DOS/4GW made Windows 95 game compatibility a little easier, but with higher stakes
A popular path to protected mode.
Just for fun: Which processors prefer sign-extended loads, and which prefer zero-extended loads?
Another pointless chart.
On writing loops in continuation-passing style, part 4
Equivalents in C# and JavaScript.
On writing loops in PPL and continuation-passing style, part 3
Explicit shared state.
On writing loops in PPL and continuation-passing style, part 2
Recursion comes back.
On writing loops in PPL and continuation-passing style, part 1
Keeping track of what to do next.
Inside STL: The different types of shared pointer control blocks
Well, some of them, at least.
Phantom and indulgent shared pointers
The phantom controls something yet holds nothing. The indulgent holds something but controls nothing.
What it means when you convert between different shared_ptrs
Changing the pointer while controlling the same object.
Inside STL: The shared_ptr constructor and enable_shared_from_this
Working together through a secret signal.
Inside STL: The shared_ptr constructor vs make_shared
Where to hide the control block.
Inside STL: Smart pointers
Simple pointers or more complicated pointers.
Inside STL: The array
It's just an array.
Inside STL: The deque, implementation
An array of (pointers to) arrays.
Inside STL: The deque, design
An array of (pointers to) arrays.
Inside STL: The unordered_map, unordered_set, unordered_multimap, and unordered_multiset
A hash table.
Inside STL: The map, set, multimap, and multiset
A red-black tree.
Inside STL: The lists
Your traditional singly- or doubly-linked list.
Inside STL: The string
An allocation, with a twist.
Inside STL: The vector
A contiguous memory block, reallocated as necessary.
Inside STL: The pair and the compressed pair
Two fields in one object, how hard can it be?
Misinterpreting the misleadingly-named STATUS_STACK_BUFFER_OVERRUN
The subcode tells you why we stopped executing, and it's rarely because of a stack buffer overflow.
How to split off an older copy of a file while preserving git line history
Variation on a theme.
Perfect forwarding forwards objects, not braced things that are trying to become objects
Before you can forward something, it needs to be a something.
On the various ways of creating Windows Runtime delegates in C++/WinRT and C++/CX
Comparing and contrasting.
Before you try to do something, make sure you can do nothing
If you can't do nothing, then don't expect to be able to do something.
Why does IAsyncAction or IAsyncOperation.GetResults() produce a E_ILLEGAL_METHOD_CALL exception?
You're asking too soon.
How to clone a Windows Runtime map in the face of possible concurrent modification, part 3
Doing it one more time, for C++/CX.
How to clone a Windows Runtime map in the face of possible concurrent modification, part 2
Applying what we learned about vectors.
How to clone a Windows Runtime map in the face of possible concurrent modification, part 1
Applying what we learned about vectors.
How to clone a Windows Runtime vector in the face of possible concurrent modification, part 4
Translating to C++/CX and dealing with some quirks of that language.
Cloning a Windows Runtime vector in the face of possible concurrent modification, denial of service?
Can you get sent into an infinite loop?
How to clone a Windows Runtime vector in the face of possible concurrent modification, part 3
Dealing with the pesky <CODE>std::vector<bool></CODE>.
How to clone a Windows Runtime vector in the face of possible concurrent modification, part 2
Trying to make a generic solution.
How to clone a Windows Runtime vector in the face of possible concurrent modification, part 1
Backing off and retrying, but the detection is the tricky part.
Why does the compiler complain about a missing constructor when I’m just resizing my std::vector to a smaller size?
The compiler doesn't know that you're shrinking.
How to wait for multiple C++ coroutines to complete before propagating failure, concluding remarks
The things that could go wrong before you even start.
How to wait for multiple C++ coroutines to complete before propagating failure, finding the awaiter
Making sure to wrap the right thing.
How to wait for multiple C++ coroutines to complete before propagating failure, wrapping the awaitable
Intercepting the exception on the front side.
How to wait for multiple C++ coroutines to complete before propagating failure, preallocating the coroutine frame
Avoiding dynamic memory allocation.
How to wait for multiple C++ coroutines to complete before propagating failure, memory allocation failure
There's no good way to report the failure, so we just have to give up.
How to wait for multiple C++ coroutines to complete before propagating failure, symmetric transfer
Avoiding stack build-up.
2023 mid-year link clearance
The tradition continues.
How to wait for multiple C++ coroutines to complete before propagating failure, custom promise
Taking things into our own hands.
How to wait for multiple C++ coroutines to complete before propagating failure, peeling away at a tuple
Iterating over a tuple recursively.
How to wait for multiple C++ coroutines to complete before propagating failure, false hope
Trying to iterate over a pack.
How to wait for multiple C++ coroutines to complete before propagating failure, unhelpful lambda
The usual trick doesn't work.
How to wait for multiple C++ coroutines to complete before propagating failure, initial plunge
Remembering the exception while finishing the other work.
What can go wrong if you release an SRWLock from a thread different from the one that acquired it?
It's not a supported scenario, so anything can happen.
How can I find out the last time a user logged on from C++?
The information is in the historically-named LANMAN APIs.
The case of the make_shared on a C++/WinRT type
Now you can't tell who's in charge.
Why is Windows using only even-numbered processors?
Spreading out the load over cores.
Why am I being told about a signed/unsigned comparison, and why only sometimes, and how can I fix it?
How the compiler back-end can influence warnings.
The case of the invalid handle despite being managed by an RAII type, part 2
Avoiding using an object after is has destructed, and maybe using a less-well-known corner of the C++ language.
The case of the invalid handle despite being managed by an RAII type
The handle remains valid for the object's lifetime, but what is the object's lifetime?
How expensive is it to create a Windows performance counter?
The cost depends on the performance counter.
SIDs are really just another a fancy way of creating unique IDs in a decentralized way
Keeping them from colliding with each other.
The move constructor that you have to declare, even though you don’t want anyone to actually call it
Forcing named return value optimization.
Reordering C++ template type parameters for usability purposes, and type deduction from the future
You want them to go first, but you also want to deduce them.
How can I register a program to auto-relaunch if it crashes or is terminated?, redux
You can get a little bit of the way there.
Pulling sleight of hand tricks in a security vulnerability report, episode 2
I see what you did there.
How can I make WiFi passwords per-user rather than per-system?
A little-known system configuration setting.
It’s great that you provide operator overloads, but it’s also nice to have names
Avoiding the need to invoke the operator explicitly as a specialized template, among other things.
C++/WinRT event handlers that are lambdas with weak pointers to the parent class, part 3
Extending to <CODE>std::weak_ptr</CODE>.
C++/WinRT event handlers that are lambdas with weak pointers to the parent class, part 2
Working out the boilerplate.
C++/WinRT event handlers that are lambdas with weak pointers to the parent class, part 1
Assessing the state of affairs.
How do I change the directory Windows uses for user profiles? revisited
You can still do it, but it's not really supported.
On writing functions that accept any specialization of a C++ template type
There are the obvious arguments, the non-obvious arguments, and the invisible arguments.
Getting a strong reference from the this pointer too late
Once destruction begins, strong references mean nothing.
How can I trigger a recalc of the mouse cursor after I changed some of my internal application state?, follow-up
You still need to filter to your window, so you don't mess up another window on the same thread.
Don’t name your header file security.h either
You may be overriding an SDK header by mistake.
On creating (and using) a transforming iterator
It lets you change the thing being iterated over, on the fly.
Speeding up the insertion of a sorted (or mostly-sorted) key list into a std::map or other ordered associative container
Provide a hint for the location of the next item.
On catching exceptions in PPL tasks
You also have to catch the exception when it comes out the end of the task chain.
What is the opposite of LVM_SORTITEMS?
How can you unring the bell?
How do I free the pointers returned by functions like GetTokenInformation?
They are all pointers back into the main memory block.
It appears that I’ve never made a complete visit to the Pacific Northwest
If the marketing department is to be believed.
Summary of the duck-typing requirements of C++ COM wrappers
Wrapping up and comparing.
What are the duck-typing requirements of C++/WinRT com_ptr?
The experiments conclude.
What are the duck-typing requirements of wil com_ptr?
The experiments continue.
What are the duck-typing requirements of WRL ComPtr?
Another round of experimentation.
What are the duck-typing requirements of ATL CComPtr?
Looking for the minimum requirements.
What are the duck-typing requirements of MFC IPTR?
Seeing what goes wrong and trying to fix it.
What are the duck-typing requirements of _com_ptr_t?
As long as you fulfill the contract, based on method names.
The case of the crash in a C++/WinRT coroutine: Unpeeling the onion
Digging deeper and deeper.
Why does XAML complain that none of the overloads of winrt::to_hstring could be used?
Look at what you are converting from and converting to.
What can I do if I don’t want my file version number to be a sequence of four integers?
The format is enforced by the Windows file format, but you can present the information in a custom way.
Why does Task Manager disappear briefly when you switch it into or out of Always on top?
Ascending to another plane of existence.
How is it even possible to cheat on a musical performance practical exam?
Nature finds a way.
A quick note about WRL’s ChainInterfaces template class
For interfaces which extend each other.
On the finer points of cancelling timers and wait objects in Windows thread pool
Assorted little details.
What’s up with this new memory_order_consume memory order?
A weaker variation of acquire.
One way to defer work when a re-entrant call is detected
Tying a string on your finger, as a reminder to yourself.
A code comment noting the steps to take when a 256th enum field is added
A note for my future self.
Why is std::hardware_destructive_interference_size a compile-time constant instead of a run-time value?
The compiler is already making compile-time assumptions about the processor; you just don't realize it.
Protecting a broker from a failing delegate
Catching them in a different way.
Protecting a broker from a failing event handler
Gotta catch them all.
The case of the unhandled exception in a brokered Windows Runtime component
Digging into the event dispatch code.
No, it is not a security vulnerability that there is no certificate of appreciation for reporting a bug
It wasn't even a bug report.
How can I find the invalid class when C++/WinRT tells me that the class may not be final?
It's in the error details.
How can I convert a WIC bitmap to a Windows Runtime SoftwareBitmap? part 4: Handing it over
Just take the whole thing.
How can I convert a WIC bitmap to a Windows Runtime SoftwareBitmap? part 3: Filling the SoftwareBitmap directly
Avoiding the intermediate buffer.
How can I convert a WIC bitmap to a Windows Runtime SoftwareBitmap? part 2: Via a buffer
Passing raw pixels across.
How can I convert a WIC bitmap to a Windows Runtime SoftwareBitmap? part 1: Via an encoded stream
We'll start with the hard way, but it gets easier.
Why is there a large gap between some of the Windows system metrics indices?
An artifact of the internal implementation.
The case of the PasswordVault.Add call that the customer thinks was hung
But was it really hung? Or did it just look that way.
An ignored exception can be misinterpreted as a hang, particularly in coroutines
I mean, execution seems to have stopped.
How do I modify the contents of a boxed Windows Runtime value?
Once it's in the box, you can't change it.
What is the maximum size of a process environment block?
There's no hard-coded limit in Windows, but maybe somebody else has a limit.
C++17 creates a practical use of the backward array index operator
Possibly more than just a curiosity.
What is this [uuid(…)] in front of my C++ class declaration?
It's an old nonstandard syntax that you should try to move away from.
If you want to watch games on your tractor, please use your own iPad
Not an approved use of the embedded system.
How can I box a std::optional into a C++/WinRT IInspectable?
There's a handy conversion for that, but you have to know where to look.
The WM_GETDLGCODE message is a query message and should not modify state
Wait until you actually get the message.
How can I try to escape the disease-ridden hot-tubs known as the TEMP and Downloads directories?
You can ask that dependent DLLs be loaded from the System32 directory.
Using the contents of a file to define an MSBuild property
A little trick that maybe should be better known.
Adventures in application compatibility: The case of the jump into the middle of an instruction from nowhere
Another rogue patcher.
How unique must the uIdSubclass parameter be when I call SetWindowSubclass?
Each one identifies an instance of the subclass for the window.
Why am I getting a weird error about promise_type when I try to write a coroutine? part 2
Are you even writing a coroutine?
Why does the usage of the initial registers of a Win32 process depend on whether it is a 32-bit or 64-bit process?
Well, I mean, it's a different processor.
On the proper care and feeding of the enigmatic GetDistanceOfClosestLanguageInList function
Thinking about how this could be used.
Exploiting C++/WinRT CRTP: Property and event declarations
They don't have to be methods; they just have to look like methods.
Mind your C++/WinRT namespaces
What you say changes meaning depending on where you are.
How can I create a git feature branch that can merge into multiple other branches?
Just work in your patch branch.
Did Vienna ever exist or was it just misinformation?
It could be neither.
The 2023/2024 Seattle Symphony subscription season at a glance
The pocket reference guide for 2023/2024.
What is the expression language used by the Resource Compiler for non-preprocessor expressions?
Oddly different for a different audience.
When should I use CS_GLOBALCLASS?
When you want to be summoned from anywhere.
From a Windows app, how can I check whether there is an app installed that implements a particular URI scheme?, part 2
Alternatives that work for unpackaged apps.
From a Windows app, how can I check whether there is an app installed that implements a particular URI scheme?
Additional function to let you see what is available.
Microspeak: Baseball card
A one-page summary, and this time we mean it.
I can create a read-only page, but why not a write-only page?
At the end of the day, it comes down to processor support.
Enumerating Windows clipboard history in PowerShell
Doing Windows Runtime things from PowerShell.
Enumerating Windows clipboard history in C++/WinRT and C#
Exploring the clipboard history API.
If you want to sort a Windows Runtime collection, you may first want to capture it into something a bit easier to manipulate
Moving everything into the same universe.
Once you give away the farm, you can’t take it back: Recovering from a rogue administrator
Who knows what happened to it while you weren't looking.
The unintentionally-expanding scope of the SEM_NOGPFAULTERRORBOX flag
Other suppressions caught in its net.
Understanding a mysterious RPC_E_WRONGTHREAD exception when we’re on the right thread
Things can go wrong in ways you may not have realized.
Why am I getting an unhandled exception from my C++ function that catches all exceptions?
Yes, you caught an exception. But that's not the one that went unhandled.
Avoiding the redundancy of adding the object files to both the primary project and its unit test
Adding another level of indirection.
Microspeak: Light reading (ironic)
Just a fun diversion.
The case of the mysterious "out of bounds" error from CreateUri and memmove
Unfolding some COMDATs.
What happens if you co_await a std::future, and why is it a bad idea?
Just waiting for something to finish.
What does it mean when my cross-thread COM call fails with RPC_E_SYS_CALL_FAILED ?
Look for an unresponsive recipient.
What are the potentially-erroneous results if you don’t pass NULL as the lpNumberOfBytesRead when issuing overlapped I/O?
It's to avoid a self-inflicted race condition.
Why are the Windows chassis hardware button hotkeys so strange?
Operating within the constraints of the system.
Adventures in application compatibility: The case of the display control panel crash on exit
When you get a 64-bit pointer, you probably should remember all 64 of the bits.
The case of the RPC_E_DISCONNECTED error thrown from await_resume
You can keep trying, but the result won't change.
A more direct and mistake-free way of creating a process in a job object
A new attribute for creating a process directly in a job object.
How can I get the original target of a shortcut without applying any 32-bit adjustments?
Disable the fancy tracking.
The frustration of finding a suitable time to hold a meeting when the participants are evenly spaced around the globe
Somebody has to suffer, but we try to make sure it's not the same person each time.
It rather involved being on the other side of this airtight hatchway: Reading the user’s saved passwords
Only the user can read their own saved passwords, so you must already have gained total control over the user.
Inside C++/WinRT: Coroutine completions: Cancellation propagation
Giving up.
Hyperlinking to Hutchison Whampoa Limited is still forbidden
Didn't make you look.
Inside C++/WinRT: Coroutine completions: Avoiding reentrant completion
Resuming the coroutine directly, rather than consuming yet more stack.
Inside C++/WinRT: Coroutine completion handlers: Disconnection
When the other end hangs up without even saying good-bye.
Inside C++/WinRT: Apartment switching: Error reporting
If you can't get back to where you started, who you gonna call?
Inside C++/WinRT: Apartment switching: COM without COM
Also known as Nano-COM.
Inside C++/WinRT: Apartment switching: Unwinding the stack
Reducing stack usage.
Inside C++/WinRT: Apartment switching: Bypassing the context callback
Reducing stack usage.
Inside C++/WinRT: Apartment switching: Unblocking the outgoing thread
Avoiding the problem of the synchronous apartment-changing callback: Let the outgoing thread do whatever it wants to do next.
Inside C++/WinRT: Apartment switching: The basic idea
Getting back to where you started.
Inside C++/WinRT: Coroutine completions: The oversimplified version
Resuming the coroutine when the asynchronous work completes.
How can I call a method on a derived class from a base class, say, to get a strong reference to the containing object?
A variety of patterns are available.
Windows Runtime asynchronous operations can fail in two different ways, so make sure you get them both
Fail me now or fail me later.
It rather involved being on the other side of this airtight hatchway: Attacking a user by modifying that user’s files
You're just attacking yourself.
A trio of dubious denial-of-service security vulnerability reports which are just style points piled on top of nothing
You could have accomplished the same thing with a garbage file.
Making C++ primitive types meaningfully movable when they have sentinel values
The value actually moves now.
Adventures in application compatibility: Querying for an internal interface
Reaching in and fiddling the internal knobs.
How should I interpret the various values of NLM_CONNECTIVITY?
Different levels of connectedness.
What does it mean when I get a mismatch from MSVC for _COROUTINE_ABI?
The two different kinds of coroutine interfaces shouldn't be mixed and matched.
It rather involved being on the other side of this airtight hatchway: Administrator attacking a domain account on the local system
You don't gain control over any other systems.
On leading underscores and names reserved by the C and C++ languages
The rules laid out.
Dubious security vulnerability: Granting access to SIDs that don’t exist yet
You can put anyone you like on your guest list, even if they don't exist.
How can I force a user to have a specific SID prefix, so that they go into a particular group?
The prefix doesn't define group membership.
Using perfect (and imperfect) forwarding to simplify C++ wrapper classes
Just call that other thing the same way you called this thing.
It rather involved being on the other side of this airtight hatchway: Gaining code execution from a Trojan horse
You already have code execution, so it's not surprising that you can gain code execution.
Opinionated notes on the Windows.Data.Json namespace
It's available if you need it, but there are some tricks and pitfalls, and you may very well have better options.
2022 year-end link clearance
Closing the book on another year.
When I create a waitable timer with a callback, do I have to wait alertably on that specific timer before the callback will run?
Any alertable wait will do.
How can I detect programmatically whether Windows is an N or KN version?
Don't check the version, just check the feature.
After importing a TLB, how do I convert from one type of _com_ptr_t to another?
Digging into the source code.
Why can’t I print when I boot Windows into audit mode?
It's not all there.
The worst-selling Microsoft software product of all time: OS/2 for the Mach 20
Count 'em on one hand.
The case of the recursively hung WM_DRAWCLIPBOARD message
Understanding why it's happening and how you can avoid it.
Is there a fixed virtual address that the system promises never to use for anything, so I can use it?
Everything is up for grabs.
Running some UI code on a timer at a higher priority than your usual timer messages, or without coalescing
You can build your own timer system.
Why doesn’t the BitLocker wizard let me save the BitLocker key on an encrypted drive?
Don't lock your keys in the car.
On the large number of ways of expressing Microsoft Visual C++ compiler versions
So many version numbers.
Why doesn’t Windows use the 64-bit virtual address space below 0x00000000`7ffe0000?
It does use it, although it doesn't look like it.
Inside C++/WinRT: IReference<T>
Reverse-engineering the usages from the code.
In C++/WinRT, how do I create or consume an IReference<T> that wraps a particular value?
Conversions to and from <CODE>IReference</CODE>.
Thank you for conference announcement, but it would help if you told me what your conference was about
There was an announcement of an all-day Microsoft-internal conference featuring a project I will call Project Enzyme. The announcement went like this: The Project Enzyme Forum is our flagship community conference that brings together engineers, project managers, data scientists, and designers from around the company to learn about Project Enzyme and get a first look at some of the exciting new improvements in the platform. Senior leaders will share their vision for Project Enyzme and how we can use it to create the next wave of cutting-edge products and experiences. Other senior leaders will participate in a ...
What does it mean when the compiler tells me that promise_type: is not a member of coroutine_traits<void>?
Applying your understanding of the coroutine transformation.
How can I do the opposite of compare_exchange and exchange if the value is different?
An exchange with itself has no effect on the value.
If you’re going to wrap a Windows Runtime event, you may as well let the wrapped event source manage the token
It keeps the original object in control.
Reminder: If you intend to use a C++/WinRT namespace, you must include that namespace’s header file
Various errors that can be traced back to breaking that one rule.
Trouble connecting to Web sites and services because of certificate errors? Check if you’re being held captive
There's a man in the middle.
Instead of a C++ template parlor trick, why not just add support based on whether the header file has already been included?
Header file inclusion order dependencies.
C++ template parlor tricks: Using a type before it is defined
You can talk about hypothetical things, hoping that a real thing shows up later.
Not even trying to cross an airtight hatchway: Calling a function in your own process by synthesizing a function pointer
You can already attack yourself in far more interesting ways.
I used FILE_FLAG_SEQUENTIAL_SCAN but it didn’t seem to speed up my sequential scanning
It triggers prefetching, but your usage pattern may mean that prefetch doesn't mean much.
Dubious security vulnerability: Reading the files in the WindowsApps folder
You already had access to those files, by virtue of the fact that they ran in the first place.
What kind of caller diagnostic information can I get from exceptions thrown by C++/WinRT and wil?, C++20 edition
The state of the art has moved forward slightly.
The case of the application that used thread local storage it never allocated
Of course it's there, isn't it? I mean, it's always been there.
How do I pass a raw pointer to a Windows Runtime function?
Raw pointers don't exist in the Windows Runtime, so you'll have to re-express it in terms of something that does.
How does JavaScript represent output parameters in the Windows Runtime?
It has to fake it.
Sometimes perfect forwarding can be too perfect: Lazy conversion is lazy
Lazy conversion is too lazy.
Microspeak: Breaking into jail
Just asking for trouble.
What kind of caller diagnostic information can I get from exceptions thrown by C++/WinRT and wil?
A survey of the current state of the art.
On Windows Runtime asynchronous operations with critical progress reports
Make the caller provide the progress handler up front.
How soon is too soon to report progress from a C++/WinRT coroutine that implements a Windows Runtime asynchronous operation with progress?
If a progress is sent to a forest but there's no one there to hear it.
Why won’t C++/WinRT let me co_await a CoreDispatcher or DispatcherQueue?
Making sure you meet the usual prerequisites.
It’s important to get the most difficult part out of the way by putting it in the title
It does much less harm there than in the body.
How does Windows decide whether your computer has limited or full Internet access?
Looking for special servers.
C++ constexpr parlor tricks: How can I obtain the length of a string at compile time?
The <CODE>constexpr</CODE>'ification of <CODE>strlen</CODE>.
If I issue multiple overlapped I/O requests against the same region of a file, will they execute in the order I issued them?
Overlapped I/O refers to temporal overlap, and that includes completion out of order.
On the dangers of giving a product feature the name “new”
It may be new today, but it won't be new tomorrow.
Why don’t Windows functions begin with a pointless MOV EDI,EDI instruction on x86-64?
Applying the hot-patch in a different way.
Why is there a system sound called Asterisk? What sound does an Asterisk make anyway?
It's to accompany the asterisk, back when we had an asterisk.
My niece is just here for the food
The important part of the trip.
In the debugger, how can I get from a projected type back to the C++/WinRT implementation?
Look behind you.
Why am I getting a RPC_E_WRONG_THREAD exception when I’m on the right thread?
It's the wrong thread from XAML's point of view.
How does the dialog manager calculate the average width of a character?
It's a simple formula, perhaps too simple.
A history of the fd_set, FD_SETSIZE, and how it relates to WinSock
The <CODE>fd_set</CODE> started out as just a bitmap.
What is a “Select Administrator”? Is that some special elite kind of administrator?
It's two different messages that combine in an interesting way.
How can I test my geolocation code on a system without a GPS?
You can use the Windows Device Portal to create a synthetic GPS.
Setting properties in C++/WinRT is done by a function call, but you need to call the function the right way
The new value is the function parameter.
Why am I seeing two WRITE requests at the same offset from a single call to WriteFile?
It started as one write, but turned into a lot of other things.
What can or should I do with the cursor handle returned by SetCursor?
You can put it back, but sometimes you need to make sure you do it before anybody else can see the change.
Why are many Windows user interface elements positioned at multiples of 4 or 8 pixels?
It depends on whose pixels you're talking about.
Why can’t I programmatically inspect the check boxes in the Security property sheet any more?
Abusing the <CODE>ISecurityInformation::<WBR>PropertySheetPageCallback</CODE> method.
What happens if my C++ exception handler itself raises an exception?
And comparing to the handling of structured exceptions.
Is it true that raising a structured exception from a structured exception handler terminates the process?
Untangling the myth.
Why is there a make_unique? Why not just overload the unique_ptr constructor?
You'll have to resolve the ambiguity, so you're still typing a lot.
Why is there a passwords.txt file on my system that’s filled with somebody else’s passwords?
It's part of an open-source password strength package.
How can I check the integrity level of my process?
A series of range checks.
The case of the memory corruption from a coroutine that already finished
The zombie coroutine.
How can I check whether the user’s network connection is roaming or metered?
The classic way and the Windows Runtime way.
One possible reason why your program crashes when submitted to the Microsoft Store, but it runs fine on your machine
Check your minimum requirements.
Clicking past the warning that you are about to cross the airtight hatchway: Vulnerable file type that you are warned about
Acknowledging the danger but complaining about it anyway.
On the overloading of the address-of operator & in smart pointer classes
Different patterns, which means you're never sure what you're going to get.
How can I perform a CopyFile, but also flush the file buffers before the destination handle is closed?
Your callback function can do things with the handle, even extend their lifetime.
The Import Address Table is now write-protected, and what that means for rogue patching
Making a potential attack vector less attractive.
The gotcha of the C++ temporaries that don’t destruct as eagerly as you thought
You have to look for the end of the full expression.
Starting on the other side of this airtight hatchway: Overwhelming the system
It'll take time for things to drain out.
Feel free to stop using IMultiLanguage2::DetectInputCodepage
You should have been keeping your eye on the code page all along.
Debugging coroutine handles: Looking for the source of a one-byte memory corruption
Applying what we know about coroutines.
I did that merge-as-cherry-pick thing, but my change still didn’t merge correctly
A case study of what goes wrong.
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?
Oh, it does pick a side. It's just that some dashes are missing.
Microspeak: Break glass
Metaphorically breaking the glass in case of emergency.
What does the C++ error “A pointer to a bound function may only be used to call the function” mean?
You got all set to call a function but forgot to call it.
Why am I receiving SHCNE_UPDATEDIR notifications that my code never generates?
You did generate them, indirectly.
How can I get WRL to link my object into its activation factory?
More magic macros.
How can I trigger a recalc of the mouse cursor after I changed some of my internal application state?
Go through the standard process one more time.
Janet Jackson had the power to crash laptop computers, follow-up
Deeper speculation by others.
Why load fs:[0x18] into a register and then dereference that, instead of just going for fs:[n] directly?
Simplifying the compiler.
Serializing asynchronous operations in C++/WinRT, gotchas and final assembly
Cancellation and abandonment.
Serializing asynchronous operations in C++/WinRT
Making them run one after the other.
Creating a lazy-start C++/WinRT coroutine from an eager-start one, part 2
Keeping a turkey in suspense.
Creating a manual-start C++/WinRT coroutine from an eager-start one, part 1
Ready, wait for it.
Serializing asynchronous operations in C#
Making them run one after the other.
The case of the APC that never arrives
Or maybe it did?
How do I consume raw COM interfaces from a Windows Runtime metadata file?
There's a handy tool for generating raw COM interfaces.
It rather involved being on the other side of this airtight hatchway: Replacing a service binary
Looking for misconfigured services.
Commonly-supported Windows shortcuts for pasting without formatting
Variations on a paste theme.
Is there any meaningful way to compare two Time Travel Debugging positions?
They are basically in chronological order, subject to the uncertainty of multiprocessing.
The case of the recursively-acquired non-recursive lock, and how to avoid the unintentional reentrancy
Watch what you do when you hold a lock.
Why am I getting a null pointer crash when trying to call a method on my C++/WinRT object?
Requirements weren't met.
The x86-64 processor (aka amd64, x64): Whirlwind tour
Pretty much a 64-bit-ification of the i386.
The AArch64 processor (aka arm64), part 25: The ARM64EC ABI
Aligning with the x86-64 calling convention.
The AArch64 processor (aka arm64), part 24: Code walkthrough
Putting theory into practice.
The AArch64 processor (aka arm64), part 23: Common patterns
Learning to recognize various code generation patterns.
The AArch64 processor (aka arm64), part 22: Other kinds of classic prologues and epilogues
Taking shortcuts, or maybe adding steps.
The AArch64 processor (aka arm64), part 21: Classic function prologues and epilogues
Implementing the ABI.
The AArch64 processor (aka arm64), part 20: The classic calling convention
How parameters are passed.
The AArch64 processor (aka arm64), part 19: Miscellaneous instructions
Sweeping up the crumbs.
The AArch64 processor (aka arm64), part 18: Return address protection
Making it even harder to smash the return address.
The AArch64 processor (aka arm64), part 17: Manipulating flags
Trying to twiddle the knobs directly.
The AArch64 processor (aka arm64), part 16: Conditional execution
Making decisions.
Janet Jackson had the power to crash laptop computers
Not an artistic judgement. Just a technical one.
The AArch64 processor (aka arm64), part 15: Control transfer
We're going places.
The AArch64 processor (aka arm64), part 14: Barriers
Keeping things in the right order.
The AArch64 processor (aka arm64), part 13: Atomic access
Don't let someone else get a word in edgewise.
The AArch64 processor (aka arm64), part 12: Memory access and alignment
The load and store part of the load/store architecture.
The AArch64 processor (aka arm64), part 11: Loading addresses
Finding a needle in the haystack of the 64-bit address space.
The AArch64 processor (aka arm64), part 10: Loading constants
Getting them into a register.
The AArch64 processor (aka arm64), part 9: Sign and zero extension
Nothing new here, but old things being used in clever ways.
The AArch64 processor (aka arm64), part 8: Bit shifting and rotation
Sliding around.
The AArch64 processor (aka arm64), part 7: Bitfield manipulation
Peeking inside the words.
The AArch64 processor (aka arm64), part 6: Bitwise operations
And their very strange immediates.
The AArch64 processor (aka arm64), part 5: Multiplication and division
Arithmetic gets harder.
The AArch64 processor (aka arm64), part 4: Addition and subtraction
Starting with the basic arithmetic.
The AArch64 processor (aka arm64), part 3: Addressing modes
The ways of accessing memory.
The AArch64 processor (aka arm64), part 2: Extended register operations
The weird ways of transforming the value in a register.
The AArch64 processor (aka arm64), part 1: Introduction
Make it a double.
Yes, the 8086 wanted to be mechanically translatable from the 8080, but why not add the ability to indirect through AX, CX and DX?
So many addressing modes, so little space.
Using C++/WinRT’s final_release to control which thread destructs your object
Once it's yours, you can take it wherever you like.
Making sure that people use make_unique and make_shared to make your object
Using a secret signal in what is required to be a public constructor.
My class derives from std::enable_shared_from_this , but shared_from_this() doesn’t work
Various cases where your enabled <CODE>shared_<WBR>from_<WBR>this</cODE> doesn't work.
Microspeak: The one-pager
Rarely ever one page long.
C++ coroutine gotcha: Falling off the end of a function-level catch
You still have to return something, but today's compilers don't warn you.
Processing a ValueSet or PropertySet even in the face of possible mutation, part 4
Processing the result differently.
Processing a ValueSet or PropertySet even in the face of possible mutation, part 3
Applying and adapting the pattern.
Processing a ValueSet or PropertySet even in the face of possible mutation, part 2
The first one there has to stay there until the work is done.
Processing a ValueSet or PropertySet even in the face of possible mutation, part 1
Watching out for iterator invalidation.
How can I provide a Windows Runtime ValueSet or PropertySet while non-intrusively monitoring changes to it?
Use the right kind of observer.
Windows Runtime observable collections don’t mix well with multithreading
Concurrent observation and mutation is a bit of a mess.
How can I write a coroutine that produces a result but keeps on running?
Returning without returning.
The empty Windows Runtime string is not just a pretty face
It really is an empty string.
How to write like Raymond: Intentional typographical errors, part 2
I can take you there, but you'll have to fix one tiny typo. Let's see if you can do that.
The case of the constructor that was being ignored
Retracing the compiler's steps.
Under what conditions can I modify the memory that I received in the form a STGMEDIUM?
If you own it, then it's yours to do with as you wish.
2022 mid-year link clearance
Another accumulation of stuff.
How can I build a URL query string in the Windows Runtime?
Pretend you're submitting a form.
How can I parse URL query string in the Windows Runtime?
There's a query parser built in, but it's a little cantankerous.
Microspeak: Inside baseball
Specialized jargon comprehensible only to a select few.
Starting on the other side of the airtight hatchway: Attacking the batch file parser
Why stop at denial of service when you have remote code execution?
The case of the mysterious over-release from deep inside the marshaling infrastructure
The tedium of monitoring reference counts.
Writing a marshal-by-value marshaler, part 2
Maybe you don't need a copy on the other side.
Understanding the marshaling flags: The free-threaded marshaler
Keeping your eye on the reference count.
Writing a compound marshaler
On the nature of streams.
On the importance of managing the stream pointer when manipulating marshal data
Making sure things are ready for the person who comes after you.
Writing a marshal-by-value marshaler, part 1
Creating an identical object on the other side.
The skeleton marshaler that does default marshaling
Starting with a marshaler that has no special features.
An initial look at the mechanics of how COM marshaling is performed
Pretend you're an oracle.
What are the various usage patterns for manually-marshaled interfaces?
The outermost simple layer, and the more complex inner layer.
Adventures in application compatibility: The case of the PC-relative indirect jump that reads from nowhere
A little too much copy/pasta.
How do I retrieve an extremely large range of cells from Excel if the clipboard functions all time out?
Maybe you shouldn't be using the clipboard.
How can I wait more than 30 seconds for a delay-rendered clipboard format to become rendered?
Provide your own delay.
Is there a maximum size for Windows clipboard data? Because I’m getting null for something I know should be there
There is no pre-set maximum size, but that null might be coming from somewhere else.
How to write like Raymond: Contacting another team for the first time
Flattery will get you in the door.
An opinionated comparison of C++ frameworks for consuming and implementing Windows Runtime types
The three leading contenders.
Assessing a read-after free for security implications: The string comparison
Can you get elevation? What are you disclosing?
Converting between Windows FILETIME and Unix time_t without having to type the magic number 116444736000000000
It's not exactly a number that you can rattle off the top of your head.
The case of the COM reference that suddenly went bad in the middle of a coroutine
Is the coroutine really to blame?
The activeCodePage manifest element can be used for more than just setting UTF-8 as the active code page
AppLocale grows up.
On passing iterables of iterables in the Windows Runtime
Different projections help you out in different ways, some more than others.
Why do rescued stack traces often have instability at the start?
Trying to pick up the scent.
Rescuing a stack trace the lazy way on x86-64 (aka amd64) after the debugger gave up
Looking for a good frame to start from.
How can I get my FileSavePicker to open in the same folder that was picked by the FileOpenPicker or FolderPicker?
Make them all share the same settings identifier.
What is the CreateExplorerShellUnelevatedTask scheduled task?
To keep Explorer running unelevated.
How does Windows decide whether a newly-created window should use LTR or RTL layout?
Gathering the algorithmic details scattered throughout the documentation into one place.
Writing a sort comparison function, part 4: descending sort
Flipping the script.
Writing a sort comparison function, part 3: spaceships
Sprinkling some C++20 magic.
Writing a sort comparison function, part 2: avoid unnecessary expense
Avoid doing the work until needed.
Writing a sort comparison function, part 1: basics
Trying to avoid the pitfalls.
How can I synthesize a C++20 three-way comparison from two-way comparisons?
Multiple ways of synthesizing a comparison.
Should I pay attention to the warning that I’m std::move‘ing from a trivial type? Part 2
It's not about the journey. It's about the destination.
Should I pay attention to the warning that I’m std::move‘ing from a trivial type? Part 1
It's just informing you that what you're doing may not have the desired effect, depending on what your desired effect was.
On ways of finding out when a C++/WinRT IAsyncAction has run to completion
Just some noodling on ideas.
A brief summary of the various versions of the Security Descriptor Definition Language (SDDL)
Things come, and rarely go.
Why does my overridable Windows Runtime method turn into a protected method, and how can I work around it?
Just an odd rule, but it's there for a reason.
On awaiting a task with a timeout in C++/WinRT
Doing the same thing, just in another language.
On awaiting a task with a timeout in C#
Putting something together from pieces you already have.
Producing an empty Windows Runtime type in C++/WinRT
How to say that you don't have anything.
What are these SIDs of the form S-1-15-3-xxx?
They are app capability SIDs.
What are these SIDs of the form S-1-15-2-xxx?
They are app container SIDs.
The case of the failed exchange of the vtable slot
Another application compatibility case.
What’s up with std::piecewise_construct and std::forward_as_tuple?
When you need to pass two sets of variadic parameters, and to work around other extremely weird edge cases.
How do I decode a #pragma detect_mismatch error?
The linker tells you a bunch of stuff. Here's what it means.
Be careful with that thing, it’s a confidential coffee maker
Just keep it under wraps.
How can I force a WriteFile or ReadFile to complete synchronously or hang, in order to test something?
You can use a named pipe.
Trying to create a factory that remembers the parameters to pass to another method
Lost in a twisty maze of universal references.
How do I access and customize the IInspectable methods of a Windows Runtime class written in C++/WinRT?
Special access methods, but normal overrides.
Class template argument deduction may be the new hotness, but we’ll always have maker functions
It's all or nothing, and sometimes you don't have all.
The Applesoft Compiler (TASC): We have the source code, in a sense
The desperation of programming under tight memory constraints.
The x86 architecture is the weirdo, part 2
It does everything differently, because of course it does.
How can I co_await on a Windows Runtime async action or operation with a timeout?
You can combine it with a timeout.
How can I tell the WIL RETURN_IF_FAILED macro that some errors are ignorable?
You can create a custom filter using things you already know how to do.
A survey of how implementations of Windows Runtime events deal with errors
All happy event delegates are alike; each unhappy event delegate is unhappy in its own way.
Notes on BitLocker and the TPM and the pre-boot password or PIN
How to get BitLocker and the TPM to play friendly.
Now that computers have more than 4MB of memory, can we get seconds on the taskbar?
Letting the CPU go to sleep.
Please repeat yourself: The noexcept(noexcept(…)) idiom
Each time you say it, it means something different.
If I am getting a DllNotFoundException from Windows 10 N, how do I get the missing DLLs?
Enter the Media Feature Pack.
All Windows threadpool waits can now be handled by a single thread
Come in and join the thread, the water's fine.
Adventures in application compatibility: The case of the RAII type that failed to run its destructor
Breaking all the rules and getting away with it.
How are Windows Runtime GUIDs represented in JavaScript?
They're strings, in various formats.
The std::invoke function does more than invoke functions
Inspiring a new level of code obfuscation.
Should I translate my window class names?
Who's going to read it?
Why am I getting the error message “This is only for weak ref support” when I try to create a C++/WinRT weak reference?
Reverse-engineering the error message.
How to become a Senior Detective, according to Murderville
A little copy pasta will take you far.
Why are there separate Program Files and Program Files (x86) directories?
Why can't we just combine them?
Why is every other line of my file mysteriously changed to nonsense Chinese characters?
Decoding another type of mojibake.
The 2022/2023 Seattle Symphony subscription season at a glance
The pocket reference guide for 2022/2023.
Behind C++/WinRT: How does C++/WinRT get the list of implemented interfaces?
Doing some template metaprogramming reverse engineering.
Behind C++/WinRT: How does C++/WinRT decide which interfaces are implemented?
Finding the code that does the interface detection.
Why does C++/WinRT say that first_interface is not a member of winrt::impl::interface_list<>?
An empty list has no first element, but why is the list empty?
A hypothetical magical musical power: The one-piece wonder
You can play one thing well, but only one.
How do I un-ignore an Outlook email thread, and how does it work?
A peek under the covers.
Injected class names: The C++ feature you didn’t even realize that you were using
Simplifying the name of what you are.
Making our multiple-interface query more C++-like, part 2
Letting you specify which interfaces are required and which are optional.
Making our multiple-interface query more C++-like, part 1
Maybe we can write a nice wrapper.
Reducing chattiness by querying for multiple interfaces at once, part 2
You can just load them into the cache.
Reducing chattiness by querying for multiple interfaces at once, part 1
The multiple-query alternatives.
How expensive is PssCaptureSnapshot? How fast is it? How much memory does it consume?
Think of it as a copy-on-write copy, like the Volume Snapshot Service.
Optimizing code to darken a bitmap, part 5
Once more, with ARM feeling.
Optimizing code to darken a bitmap, part 4
Bringing out the big SIMD guns, for x86 at least.
Optimizing code to darken a bitmap, part 3
Jumpless conditionals via masking.
Optimizing code to darken a bitmap, part 2
Exploiting parallel arithmetic.
Optimizing code to darken a bitmap, part 1
Starting with the basics.
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?
No, but you sort of knew that deep down.
Filtering out fake keyboards from the GetRawInputDeviceList function
Maybe look to see if it has any keys.
How can I detect whether the system has a keyboard attached? On the GetRawInputDeviceList function
You can enumerate the input devices and see if there's a keyboard.
How does Windows decide what instructions to provide for unlocking the PC?
It sniffs around at your hardware capabilities.
Zero-cost exceptions aren’t actually zero cost
Shifting the cost to the exceptional path.
How can I monitor changes to the reference count of a C++/WinRT object?
A little cookbook.
COM asynchronous interfaces, part 9: Asynchronous release, assembling a solution
Juggling the references in the right way.
COM asynchronous interfaces, part 8: Asynchronous release, the problems
If you don't need something any more, then you usually don't really care when it gets taken away.
COM asynchronous interfaces, part 7: Being called directly when the operation completes
Becoming part of the system.
COM asynchronous interfaces, part 6: Learning about completion without polling
You can peek at the handle hiding inside the synchronization interface.
COM asynchronous interfaces, part 5: The unreliable server
Trying not to hang when the server is hung.
COM asynchronous interfaces, part 4: Doing work while waiting for the asynchronous operation
Just checking in on how things are going.
COM asynchronous interfaces, part 3: Abandoning the operation after a timeout
Waiting a little while, but not forever.
COM asynchronous interfaces, part 2: Abandoning the operation
Simply losing interest.
COM asynchronous interfaces, part 1: The basic pattern
Letting things run on their own, and then coming back for the answer later.
Notes on COM aggregation: How do you implement tear-offs in an aggregated object?
Keeping the controlling unknown in the know.
Notes on COM aggregation: Obtaining a pointer to your aggregated partner without introducing a reference cycle
Putting your thumb on the scale.
How can I find out which processor architectures are supported via emulation by the current system?
Fortunately, there's a special function for that, or at least for enough of that to serve your needs.
The cats sitting on a fence in early builds of Windows 8
Something to look at when all is lost.
On finding the average of two unsigned integers without overflow
Another code golfing adventure.
The case of the stack overflow exception when the stack is nowhere near overflowing
There's a problem with the stack that prevents it from growing, so you could consider than an overflow.
A closer look at the stack guard page
It is there to detect stack growth, but only if the stack grows into it.
Gotcha: C++/WinRT weak_ref.get() doesn’t get the weak reference; it gets the strong reference
What traditionally goes by the name <CODE>lock()</CODE>.
How do I customize the color of the Windows blue screen?
It's hard-coded now, sorry.
Why does the Windows debugger engine show a bunch of hex digits after one of the DLL names?
It's trying to disambiguate name collisions.
How can I recognize whether two handles refer to the same underlying file?
Exploring several avenues, hoping one of them leads somewhere.
How can I recognize file systems that don’t support 64-bit unique file identifiers?
It's buried somewhere in the specification.
What are these weird internal Visual C++ runtime functions named NLG?
They are part of exception handling.
I deleted a file from Explorer, but it came back when I refreshed, and I get Access Denied if I try to delete it again
The file is circling the drain, but it's not gone yet.
The MainWindowHandle property is just a guess based on heuristics
If you really need to find your main window, you'll have to come up with something more determinstic.
Fixing the crash that seems to be on a std::move operation
Getting the order of evaluation to be what you want.
The mystery of the crash that seems to be on a std::move operation
But is that really what's happening?
The error code you get might not be the one you want
Some error codes are contractual, but most aren't.
How to write like Raymond: The typing-saver
One of my little catch phrases.
C# and C++ type aliases and their consequences
Just some idle thoughts, and what it means for debugging.
Resolving confusion over how to return from a C++ coroutine
You have a few options, but you have to stay with it.
The oracle always tells the truth, even when it is wrong: COM method calls with a user-defined type as a return value
What you ship becomes the truth.
Standing on the shoulders of giants: Let the compiler tell you what the ABI is
Consult the oracle.
Jumping into the middle of an instruction is not as strange as it sounds
It's just another trick for saving space.
How can I detect that a thread pool work item is taking too long?
Call in a watchdog.
How do I upgrade a 32-bit tick count to a 64-bit one?
Fortunately, there's a 64-bit one sitting nearby.
Filling in some gaps in the story of Space Cadet Pinball on 64-bit Windows
The story as I experienced it.
How do I prevent folder verbs intended for file system directories from showing up in my shell extension’s virtual folder’s context menu?
They shouldn't be there in the first place.
My Excel spreadsheet doesn’t scroll even though I can use the arrows to move around
Freeze, and put your hands up!
Speculation on the design decisions that led to the common ABI for C++ coroutines
Considering some alternatives.
2021 year-end link clearance
Another trip around the sun.
The case of the programs that were launched with impossible command line options
Death and resurrection, unsuccessfully.
The C++/CX String^ is not an object, even though it wears a hat
A strange beast that thing is.
You can’t copy code with memcpy; code is more complicated than that
There's more to code than just instructions.
A rejected attempt to inject pseudo-physics into Windows 8 toast notifications
Like a mischievous rubber band flung across the screen.
How do I add custom controls to the common file open or file save dialogs?
A survey of the history of customization, leading to the present.
The Thanksgiving to Christmas sales nationwide of the VIS could be tabulated in an unsigned char
One of the great duds of console gaming history.
It’s easy to get data into the GPU, but harder to get it out
The continuing evolution of graphics memory.
How do I programmatically reposition monitors in a multiple-monitor system?
The magic phrase is <CODE>DM_POSITION</CODE>.
You thought Windows drivers from 2006 were old, wait’ll you see the Intel drivers from 1968!
It's the same driver date hack, just even more extreme.
Why do I have to add one when setting a class background brush to a system color?
To make sure it's not null.
Why is the stack overflow exception raised before the stack has overflowed?
You need some stack to deal with the exception.
Why does the precise point at which I get a stack overflow exception change from run to run?
The system is trying to introduce some unpredictability.
What does “Do not launch, but debug my code when it launches” mean?
Don't launch my code when it launches? Does that even make sense?
Embarrassing product names created: Windows CE
You do all you can, but at the end of the day, it's not yours to control.
Dubious security vulnerability: Accessing information across accounts after changing email address
It's still you, just with a different online façade.
It’s okay to be contrary, but you need to be consistently contrary: Going against the ambient character set
Code different.
If you’re going to configure a header file, you have to do it before you include the header file
It sounds obvious, but you can be faked out.
Using CRTP to your advantage: Simplifying overloaded Windows Runtime method projections in C++/WinRT
As long as the wrapper can call it, you can implement it any way you like.
What happens when a hot air balloon lands in your yard?
Break out the bubbly.
It rather involved being on the other side of this airtight hatchway: Producing malicious data in a kernel driver
Sure, you can fool other people, but you can do far more than that already.
Compiler error message metaprogramming: Helping to find the conflicting macro definition
Shaping the code so a required diagnostic will be useful.
How can I produce a C-style array from a Windows Runtime asynchronous operation?
No good solutions, but some workarounds.
How do I receive ownership of a C-style array in a Windows Runtime component?
The implementation side of the role reversal.
How can I transfer ownership of a C-style array to a Windows Runtime component?
Survey the options and realize that the only choice is to go backward.
How can my C++/WinRT component pass a std::vector back to the caller?
Implementing the ReceiveArray pattern.
How did Windows 3.1’s virtual machine manager get the information to show in the text-mode Alt+Tab switcher?
Getting by with a little help from a friend.
The two products may be identical, but they are not the same
No price-matching for you.
I called AdjustTokenPrivileges, but I was still told that a necessary privilege was not held, redux
Did any privilege adjustment occur at all?
How do I pass an array of variable-sized PROPSHEETPAGE structures to PropertySheet?
It's "just" an array of variable-sized structures.
Appending additional payload to a PROPSHEETPAGE structure
Taking it along for the ride.
Every business process secretly wants to fail
At least, that's how it looks from the outside.
A reminder about the correct way of accessing and manipulating the position of icons on the desktop
There's an interface for that. Please use it.
Why is my C++/CX ref class forbidden from having public methods that are templates or mention, say, std::vector?
C++/CX overloads the class member access control keywords to control metadata generation.
What does the CompileAsWinRT Visual Studio project option mean?
And why it's badly-named.
The mental model for StartThreadpoolIo
It's internally managing a reference count.
Microspeak: Righteous
A colloqualism that has become a preferred adjective.
A practical use for GetHGlobalFromStream when sharing was never your intention
This may even have been its original purpose.
Another way of looking at C++ reverse iterators
It's the same thing, just going in the opposite direction, right?
I sort of knew that I’m a bad flute player, but I guess this proves it
The fault is in ourselves, after all.
The inside story of the outside investigation of SoftRAM 95
It had a plan, but didn't quite execute on it.
How am I supposed to create children of the Win32 tab control?
They look like children, but they're not.
If your domain name parser can’t handle internationalized domain names, then maybe that’s your parser’s problem
Don't blame someone else for letting strange domain names reach you.
Restoring support for pre-standardization coroutine free awaiters for even older code bases
Connecting the dots, and reaching back to an earlier time.
The case of the C++/WinRT cached factories that pointed into freed memory
Developing theories that match the evidence.
How can I prevent myself from accessing a lambda captured variable or a parameter after I’m done with it?
Name-hiding on purpose.
A capturing lambda can be a coroutine, but you have to save your captures while you still can
Save it all before it disappears.
The focus rectangle says, “I’m not orange. I’m just drawn that way.”
How does <CODE>DrawFocusRect</CODE> draw the focus rectangle?
Why do all this coroutine stuff if you can just use std::future?
Escape from PPL.
Giving a single object multiple COM identities, part 4
Simplifying the pattern.
Giving a single object multiple COM identities, part 3
Returning to the scene of the crime.
Giving a single object multiple COM identities, part 2
Trying to develop a slightly more efficient multi-headed snake.
Giving a single object multiple COM identities, part 1
Like a multi-headed snake.
A very brief introduction to patterns for implementing a COM object that hands out references to itself
We'll look at many choices, but focus on one.
Renaming a file is a multi-step process, only one of which is changing the name of the file
If you're going to swoop in, make sure to swoop in carefully.
Why isn’t MapDialogRect mapping dialog rectangles?
Maybe you don't have a dialog.
My code crashed when I asked WIL to convert an exception to an HRESULT, did I throw an improper exception type?
Digging into the failure more closely.
That time we had a network outage due to unexpected hunter activity
Watch where you're pointing that thing.
How can I get the screen reader to read out an error message that I displayed inline on a page?
Make it a live region.
What does the SizeOfImage mean in the MODULEINFO structure?
It's the size in terms of mapped address space when loaded.
Why does GetModuleInfo fail to produce an entry point for executables?
Because it's getting the information from the loader, who has no use for such things.
Local variables are different from parameters in C++ coroutines
You tend to think of them the same, but they destruct differently.
The happy hand: A puzzle about odd names in Azure DevOps
Who's renaming everything into something cute?
Is there a way that my macro can detect that it’s running in a C++ coroutine?
You are part of the decision.
What can I do about timer build-up when waiting for COM outbound calls to complete?
You'll have to drain them out yourself.
Debugging coroutine handles: The Microsoft Visual C++ compiler, clang, and gcc
Peeking behind the curtain.
Why is the main() function always at address 0x00401000 in a simple program?
When multiple technical decision add up, literally.
Not from inside the Redmond Reality Distortion Field: Microsoft Streets and Trips support for ferries
From somebody else's reality distortion field.
Some lesser-known powers of std::optional
Things it does that you may not know about.
The subtleties of CreateStreamOnHGlobal, part 4: Non-movable memory
Fear and reallocation.
The subtleties of CreateStreamOnHGlobal, part 3: Suppressing the deletion of a shared HGLOBAL
Trying to set up joint custody.
The subtleties of CreateStreamOnHGlobal, part 2: Suppressing the deletion of an unknown HGLOBAL
You don't know what it is, but you said you don't want it deleted automatically.
The subtleties of CreateStreamOnHGlobal, part 1: Introduction and basic usage
Developing the mental model.
Why am I getting an unresolved external from C++/WinRT if it is a header-only C++ library?
Maybe you didn't get all of the headers.
The case of the UWP application that crashes at launch on Windows 10X
Look before you leap.
Why is there trailing garbage when I try to decode the bytes of a HttpContent object?
You need to know when to stop.
Converting between UTF-8 strings and UTF-16 strings in C++/WinRT
A pair of conversion functions.
The CertUtil program will decode Windows error codes, and in a variety of formats
Even more versatile than <CODE>NET HELPMSG</CODE>.
What does this mean? The caller specified wait timed out before the operation completed because a host termination is in queued
An error message written with infrastructure-colored glasses.
Adventures in application compatibility: The case of the wild instruction pointer that, upon closer inspection, might not be so wild after all
The search for clues leads to an unexpected place.
The C++ implicit assignment operator is a non-ref-qualified member, even if the base class’s assignment has a ref-qualifier
Does that count as dis-qualification?
How do I set the alpha channel of a GDI bitmap to 255?
Most things destroy the alpha channel, but there's a way to bring it back, or at least make it opaque.
Microspeak: Persona
A template for a prototypical user.
The C++/WinRT query_interface_tearoff extension point, and using it for COM aggregation
For adding your own <CODE>QueryInterface</CODE> magic.
Ordering asynchronous updates with coroutines, part 5: Bowing out via cancellation
Using the built-in way of stopping a coroutine.
Ordering asynchronous updates with coroutines, part 4: Bowing out, explicit version
Realizing you're not the one.
Ordering asynchronous updates with coroutines, part 3: Let them all compete, but only one wins
Everybody tries, but only one wins.
Ordering asynchronous updates with coroutines, part 2: Restart with hand-off
Everybody just waits their turn.
Ordering asynchronous updates with coroutines, part 1: Mutual exclusion
Everybody just waits their turn.
I declared my Windows Runtime method as accepting an array by reference, but it always arrives empty
You were only meant to put things into the box, not look at what was already there.
Adventures in application compatibility: The cost of forgetting to specify a calling convention
Cleaning up behind mistakes of the past.
Looking at world through __stdcall-colored glasses
It's the default, or at least it's my default.
Notes on the Seattle Symphony’s expanded concert schedule for 2021–2022 season
More concerts, more options.
What are the consequences of increasing the per-process GDI handle limit?
Striking a balance.
The various ways of moving between C++/WinRT and classic COM
Crossing to the other side.
How can I break down a shell item in the same way as the breadcrumb bar?
Gathering the folders that lead up to a shell item, walking up the tree, or walking from the root to the leaf, and then obtaining the desired name.
In C#, how do I get the descriptive text for an HRESULT?
You can pretend it was an exception.
The Windows Runtime PassArray is a read-only array, even though it isn’t declared const
Because in most languages, there is no such thing as const.
How to sneak the Windows 95 credits screen into the build without anybody noticing
Write it in an obscure language.
C++/WinRT nasty gotcha: winrt::param::hstring constructed from std::wstring_view requires null termination
An additional constraint not part of the rules.
How do I find out the size of the mouse cursor?
Well, first you have to decide which one you want to measure.
How to pwn an unattended laptop, according to Humans
According to television.
What is the deal with the SM_CXCURSOR system metric?
A metric from an earlier, simpler time.
What’s with all of the references to “dude” in the accessibility header files?
A catch phrase from long ago.
Is it expected that custom default pinned taskbar items via LayoutModification.xml keep coming back each time the user logs on?
Yes, so you need to plan accordingly.
What are these dire multithreading consequences that the GetFullPathName documentation is trying to warn me about?
The current directory is volatile, so plan accordingly.
Resolving the ambiguity when your C++ class inherits from multiple base classes that have the same method
Steer the compiler toward the method you want.
How can I find the heap that a memory block originally came from, so I can free it properly?
You'll have to keep track of it yourself.
How can I prevent my UWP app from showing up in the Start menu?
Deny its app list entry.
Why did the old RAID database use a signed 16-bit integer for its record count? Why not unsigned, or a 32-bit integer?
You have to understand decisions in context, and that includes knowing the problem it was trying to solve.
Why am I getting a weird error about promise_type when I try to write a coroutine?
Digging into the coroutine infrastructure for the answer.
Using Windows Runtime interop methods from C++/WinRT: Some helper functions
Getting the interface, and the capturing from it.
An example of using Windows Runtime interop methods from C++/WinRT: RequestTokenForWindowAsync
Understanding how the C++/WinRT interop pieces fit together.
What is a static Windows Runtime class, how should I express it, and when should I use it?
The underlying question is "Can you even make one?"
Why are all of the retail demo names male?
For localization consistency.
How can I figure out which object is being hosted in an instance of dllhost?
Finding the object.
Why doesn’t my asynchronous read operation complete when I close the handle?
Because the file isn't closed yet.
On the interaction between the FILE_FLAG_NO_BUFFERING and FILE_FLAG_WRITE_THROUGH flags
Let's fill in another table.
How can I prevent the mouse from moving in response to touch input?
You need to make your program pointer-aware.
Twitter misdetected the 2011 Build conference keynote as a denial-of-service attack
Just a lot of excited developers.
Diagnosing why your batch file prints a garbage character, one character, and nothing more
Following the clues you have.
The history of passing a null pointer as the key name to RegOpenKeyEx
It doesn't mean anything special any more, but it once did.
The case of the strange NT-style path that was discovered by SearchPath
Remember where it searches.
I know I can change the color of the DC pen, but what about the other attributes?
They're locked in, sorry.
Why does the New menu even exist for creating new empty files?
You have to open the file anyway to make it useful, so why not just open the program directly?
C++11 braced initialization made the impossible possible (and how to fix it so it stays impossible)
Braced initialization to the rescue, or denied.
What’s the difference between throwing a winrt::hresult_error and using winrt::throw_hresult?
It affects the error origination.
On proper handling of buffers in COM and RPC methods
The RPC layer deals with most of the problems for you, assuming you're using the RPC layer.
How to perform more complicated search and replace-style renaming in a batch file
Try something other than wildcards.
How did copying and renaming with wildcards work in MS-DOS?
By lining up two parallel arrays.
Why do smart pointers null out the wrapped pointer before destroying it?
It's not a race condition, but it's some condition.
On the perils of holding a lock across a coroutine suspension point, part 3: Solutions
How to avoid the trap.
On the perils of holding a lock across a coroutine suspension point, part 2: Nonrecursive mutexes
Another way things can go wrong.
On the perils of holding a lock across a coroutine suspension point, part 1: The set-up
One way things can go wrong.
How to act like you know Chinese even though you don’t, episode 2
Find the magic word.
What happens if I use a squash instead of a true merge when performing one of the git tricks?
In many cases, the merge is where the magic is.
How a basketball became a featured instrument in a Sting song
It's all in the name.
Is it okay to call MapViewOfFile on the same mapping handle simultaneously from different threads?
Or do you have to enforce serialization to ensure both calls succeed?
Studying linker error messages to find the cause of the unresolved external: Character sets
Puzzling out why the symbols don't match exactly.
2021 mid-year link clearance
A collection of stuff that has accumulated.
What should the CPU usage be of a fully-loaded CPU that has been throttled?
A valid difference of opinion.
The initializing constructor looks like an assignment, but it isn’t
There is no assignment going on; it's just a quirk of syntax.
The ARM processor (Thumb-2), part 20: Code walkthrough
Putting together what we've learned, with a surprise.
The ARM processor (Thumb-2), part 19: Common patterns
Code sequences you will learn to recognize.
The ARM processor (Thumb-2), part 18: Other kinds of prologues and epilogues
Taking shortcuts and combining steps, or omitting them entirely.
The ARM processor (Thumb-2), part 17: Prologues and epilogues
Implementing the receiving end of the calling convention.
The ARM processor (Thumb-2), part 16: The calling convention
Pretend it's on the stack, even if it isn't.
The ARM processor (Thumb-2), part 15: Miscellaneous instructions
The stuff that didn't fit anywhere else.
The ARM processor (Thumb-2), part 14: Manipulating flags
Reaching in and flipping the switches.
The ARM processor (Thumb-2), part 13: Trampolines
The overly-uniform program counter register strikes again.
The ARM processor (Thumb-2), part 12: Control transfer
Let's go places.
The ARM processor (Thumb-2), part 11: Atomic access and barriers
Doing things one at a time.
The ARM processor (Thumb-2), part 10: Memory access and alignment
It's just loads and stores.
The ARM processor (Thumb-2), part 9: Sign and zero extension
Making small things bigger.
The ARM processor (Thumb-2), part 8: Bit shifting and bitfield access
That barrel shifter again.
The ARM processor (Thumb-2), part 7: Bitwise operations
Flip-flopping the bits.
The ARM processor (Thumb-2), part 6: The lie hiding inside the CMN instruction
Don't let the name fool you.
The ARM processor (Thumb-2), part 5: Arithmetic
Starting with basic mathematics.
The ARM processor (Thumb-2), part 4: Single-instruction constants
Flaunt your barrel shifter if you've got it.
The ARM processor (Thumb-2), part 3: Addressing modes
It's a load-store architecture, but with rather fancy loads and stores.
The ARM processor (Thumb-2), part 2: Differences between classic ARM and Thumb-2
Squeezing into a 16-bit instruction size.
The ARM processor (Thumb-2), part 1: Introduction
Moving into the present.
On the proper care and feeding of the default_overload Windows Runtime attribute
Generally avoid it, but if use it you must, at least follow these rules.
How can I convert between IANA time zones and Windows registry-based time zones?
ICU to the rescue.
How ownership of the Windows clipboard is tracked in Win32
A simple model, complicated by the reality of misuse.
Why are device-independent bitmaps upside down?
Well, it depends on what you consider to be right-side up.
On static methods in the Windows Runtime and C++/WinRT
Transforming the ABI into a projection.
Obtaining attributed network usage information from the Windows Runtime
Breaking it down by application.
Obtaining network usage information from the Windows Runtime
Getting your foot in the door with the NetworkInformation class.
Awaiting Windows Runtime asynchronous operations from C# desktop apps
Need to find the awaiter.
The blessing of the leading zero
Sometimes it's not a curse.
Why did Windows 95 keep window coordinates at multiples of 8?
Because sub-byte memory access is really annoying.
Why isn’t my shell namespace extension getting every single DragOver mouse message?
Trying to avoid too much chattiness for things that aren't important.
Drag/drop effects: The little drop information box
Updating the description.
Using Explorer’s fancy drag/drop effects in your own programs
Accessing those pre-made shell drop effects.
Why does the mouse cursor jump a few pixels if you right-click on the Start button?
To give you a head start.
What are the page sizes used by Windows on various processors?
Usually there was no choice, but sometimes there was.
A subtle way your await_suspend can access the coroutine frame when it shouldn’t
Hiding in the coroutine machinery.
Is std::exception_ptr nothrow constructible and assignable?
Yes, buried in the fine print.
Why is coroutine_handle::resume() potentially-throwing?
It enables a very specific usage scenario.
A map through the three major coroutine series
For your casual reading convenience.
C++ coroutines: Promise constructors
Snooping on the coroutine parameters, with a gotcha.
C++ coroutines: Converting among tasks that use the same promise
Keeping the promise in the dark.
C++ coroutines: Waiting synchronously for our coroutine to complete
Using the extension point for another purpose.
C++ coroutines: Adding COM context support to our awaiter
Getting into the correct context on resume.
C++ coroutines: Snooping in on the coroutine body
Transformers are robots in disguise.
C++ coroutines: How do I create a coroutine that terminates on an unhandled exception?
You need to get inside the coroutine.
C++ coroutines: What does it mean when I declare my coroutine as noexcept?
The noexcept keyword doesn't mean what you think.
C++ coroutines: Associating multiple task types with the same promise type
Using the special initialization rule for <CODE>get_<WBR>return_<WBR>object</CODE>.
C++ coroutines: Improving cold-start coroutines which complete synchronously
Avoiding stack build-up.
C++ coroutines: Cold-start coroutines
On your mark, get set, wait for it!
C++ coroutines: Getting rid of our atomic variant discriminator
Don't look unless you know it's safe.
C++ coroutines: Allowing the awaiter to be destroyed while suspended
We were already there.
C++ coroutines: Getting rid of our reference count
It never goes up. It only comes down.
C++ coroutines: Getting rid of our mutex
We can capture the progress in a single value.
Pivot points and financial numerology
It will or it won't. That's the beauty of it.
C++ coroutines: Making it impossible to co_await a task twice
Always keep moving: Make the <CODE>co_await</CODE> consume the task.
C++ coroutines: Tradeoffs of making the promise be the shared state
Are you meant to be ephemeral, or are you intended to be durable?
C++ coroutines: The lifetime of objects involved in the coroutine function
Follow them as they pop into existence and vanish.
C++ coroutines: Managing the reference count of the coroutine state
Are we done yet?
C++ coroutines: Awaiting the simple_task
Let me know when it's ready.
C++ coroutines: Accepting types via return_void and return_value
A little bit of SFINAE tweaking.
C++ coroutines: Building a result holder for movable types
Not that kind of movable type.
C++ coroutines: Making the promise itself be the shared state, the outline
Now we do it.
C++ coroutines: Making the promise itself be the shared state, the inspiration
Just be it.
C++ coroutines: What happens if an exception occurs in my return_value?
What happens if you can't save the result?
C++ coroutines: The initial and final suspend, and improving our return_value method
Why would you stop before you start?
C++ coroutines: Basic implementation of a promise type
Filling in the diagram with code.
C++ coroutines: The mental model for coroutine promises
We start by drawing pictures.
Creating a task completion source for a C++ coroutine: Failing to produce a result
Stowing an exception.
Creating a task completion source for a C++ coroutine: Producing nothing
Nothing is produced, but you still want to know that the production completed.
SEO spammers don’t really understand who they spammed
Maybe we can help you.
Creating a task completion source for a C++ coroutine: Producing a result with references
Carefully preserved to prevent decay.
The 2021/2022 Seattle Symphony subscription season at a glance
The pocket reference guide for 2021/2022.
Creating a task completion source for a C++ coroutine: Producing a result
Let's call it a result holder.
Creating other types of synchronization objects that can be used with co_await, part 10: Wait for an event to clear
Something new.
Creating other types of synchronization objects that can be used with co_await, part 9: The shared mutex (continued)
Fixing some problems.
Creating other types of synchronization objects that can be used with co_await, part 8: The shared mutex
Two different kinds of waiting and releasing.
Creating other types of synchronization objects that can be used with co_await, part 7: The mutex and recursive
The mutex and recursive mutex as strange beasts in the world of coroutines.
Creating other types of synchronization objects that can be used with co_await, part 6: The semaphore
The asynchronous semaphore.
Creating other types of synchronization objects that can be used with co_await, part 5: The auto-reset event
The asynchronous auto-reset event.
Creating other types of synchronization objects that can be used with co_await, part 4: The manual-reset event
The asynchronous manual reset event.
Creating other types of synchronization objects that can be used with co_await, part 3: Parallel resumption
Resuming waiting coroutines in parallel on the thread pool.
Creating other types of synchronization objects that can be used with co_await, part 2: The basic library
Distilling the pattern to its essence, and the building back up.
Creating other types of synchronization objects that can be used with co_await, part 1: The one-shot event
First a little demonstration.
Creating a co_await awaitable signal that can be awaited multiple times, part 6
Looking back on what we've done.
Creating a co_await awaitable signal that can be awaited multiple times, part 5
Discussion of what we've done so far.
Creating a co_await awaitable signal that can be awaited multiple times, part 4
Why allocate memory when you can have it given to you?
Creating a co_await awaitable signal that can be awaited multiple times, part 3
Doing it all ourselves, without any need to go into kernel mode.
Creating a co_await awaitable signal that can be awaited multiple times, part 2
Because sharing is caring.
Creating a co_await awaitable signal that can be awaited multiple times, part 1
Sort of like an event.
What does error E_ILLEGAL_DELEGATE_ASSIGNMENT mean?
A delegate was assigned when not allowed, but when is it allowed?
What does it mean when a call fails with 0x8000001F = RO_E_BLOCKED_CROSS_ASTA_CALL?
Waiting wouldn't have helped.
What is so special about the Application STA?
Basically, it blocks re-entrancy.
Why does Task Manager tell me that I have a Startup program named Program?
It's a program that didn't register itself properly.
French is a very fragile language, or at least it seems so from the stories I hear
The slightest variation renders it incomprehensible.
How do I reset my PIN complexity requirements after removing a work account from Windows 10?
You need to remove the PIN and add it back.
How can I prevent a Windows Runtime WebView from loading any content beyond the initial request and its redirects?
Follow the bouncing redirect.
How can I prevent a Windows Runtime WebView from loading any content beyond the initial request?
You can intercept every resource request.
How can I return custom content for specific URLs requested by a Windows Runtime WebView?
Intercepting the attempts to contact the outside world.
Hardware engineers solve a usability problem with the PS/2 connector, but inadvertently create a new one
What's the difference between a mouse and a keyboard?
The COM static store, part 6: Using C++ weak references
A quicker way to get to what you have.
The COM static store, part 5: Using COM weak references
Avoiding having to go through the static store at all.
The COM static store, part 4: Aggregating into a single object
Batch all the things you need into a single object.
The COM static store, part 3: Avoiding creation of an expensive temporary when setting a singleton
Don't create one unless you really need one.
The COM static store, part 2: Race conditions in setting a singleton
There can be only one, so don't end up with two.
The COM static store, part 1: Introduction
Communal storage for COM things.
How do I get a foothold in the neutral apartment?
You can explicit ask for its context.
Usage patterns for winrt::unbox_value_or
Two templates, many patterns.
Why is there no useful information in the RetailInfo class?
It's just marketing nonsense.
A metric that is consistently at 100% is probably broken
They say that you get what you measure.
Why am I being told my fire_and_forget coroutine is not returning a value?
Fire-and-forget coroutines don't return a value, do they?
Autoscrolling on drag, part 5: Adding wiggle-to-scroll to escape velocity
Reintroducing a bug that's now a feature.
Autoscrolling on drag, part 4: Dynamic autoscroll based on escape velocity
Get a good running start.
Autoscrolling on drag, part 3: Dynamic autoscroll based on mouse position
Pull the rubber band more taut.
Autoscrolling on drag, part 2: Why does scrolling go faster if I wiggle the mouse?
You're tickling the adjustment code outside its normal cycle.
Autoscrolling on drag, part 1: Basic implementation
Setting the groundwork.
How do I protect myself against a COM call that can hang? I’m already running the server out-of-process.
You can cancel the call, and if the server ignores you, it's left working on a canceled operation.
What happens to the value returned from the function passed to QueueUserWorkItem?
Nothing. Nothing at all.
How do I disassociate a thread from an I/O completion port?
Escaping the trap.
Why did I lose 3D display mode when I upgraded to the next version of Windows 10?
It's not the Windows version that lost it. It's your display driver that lost it.
How can I prevent another program from showing a thumbnail preview in the taskbar?
You can't, really. It's not your window.
The perils of the accidental C++ conversion constructor
Single-parameter constructors are also conversions.
How can I write a C++ class that iterates over its base classes?
Variadic templates to the rescue.
The misleading MIDL error message: MIDL5023: The arguments to the parameterized interface are not valid
They aren't valid, but then again, nothing would have been.
Why am I receiving SHCNE_UPDATEDIR notifications that my code never generates?
You did generate them, indirectly.
How did I find the old Windows binaries and compilers for the processor retrospective series?
Going through old virtual boxes of stuff.
The case of the crash during the release of an object from an unloaded DLL during apartment rundown
The great escape from the confines of the custom COM context.
What happens if I give contradictory values for the stack commit and stack reserve?
The system will try to massage the values into something less unreasonable.
How can I tell whether my process is running as SYSTEM?
Check your token.
Additional helpful pseudo-handles: The process token, the thread token, and the effective token
For quick queries.
How can I write a program that monitors another window for a change in size or position?
Accessibility hooks come to the rescue once again.
I’d like an IUnknown, I know you have many, I’ll take any of them
Taking the first one is as good as any other.
How can I create a non-circular tab order, or some other type of custom ordering in my Win32 dialog?
Taking things into your own hands.
Why are the C and C++ compilers giving me error messages about int when my code doesn’t mention int?
It's a manufactured <CODE>int</CODE>.
What are these duplicate services whose names differ just by random characters at the end?
You get a service, and you get a service, everybody gets a service!
Why is the HSHELL_WINDOWDESTROYED notification raised when a window is hidden, even if it hasn’t been destroyed?
Taskbar-colored glasses.
How can I emulate the REG_NOTIFY_THREAD_AGNOSTIC flag on systems that don’t support it? part 5
Using the new thread pool functions.
How can I emulate the REG_NOTIFY_THREAD_AGNOSTIC flag on systems that don’t support it? part 4
Onward to coroutines.
How can I emulate the REG_NOTIFY_THREAD_AGNOSTIC flag on systems that don’t support it? part 3
Getting more asynchronous.
How can I emulate the REG_NOTIFY_THREAD_AGNOSTIC flag on systems that don’t support it? part 2
Asking the thread pool for help.
How can I emulate the REG_NOTIFY_THREAD_AGNOSTIC flag on systems that don’t support it? part 1
An exercise from long ago.
What should the state of a moved-from object be?
It's formally unspecified, but there may be informal expectations.
On the ways of finding a dispatcher for the current thread in the Windows Runtime
You have to look around, but be careful not to trip over anything.
Why does PF_VIRT_FIRMWARE_ENABLED return false even when virtualization is enabled in the firmware?
It may be enabled, but it's not enabled for <I>you</I>.
Lost Windows feature: The Horizon
Unlike the real horizon, this one is up close.
How do I avoid race conditions in WaitOnAddress where the wake happens before I enter the blocking state?
You're waiting on it wrong.
Parsing ETL traces yourself, part 3: The TraceProcessor
Getting it from the same source as the Windows Performance Analyzer.
Parsing ETL traces yourself, part 2: The EventLogReader
For true programmatic processing of classic ETL events.
Parsing ETL traces yourself, part 1: wpaexporter
A simple converter that spits out comma-separated values.
How did Windows open a portal to another dimension when reporting a program error?
A momentary tear in the space-time continuum.
Why does CreateWindowEx take the extended style parameter as its first parameter instead of its last?
It sure looks like a strange place to add a new parameter.
The humor hiding behind “JavaScript error: Semicolon expected”
Apparently not automatic enough.
Additional notes on the various patterns for passing C-style arrays across the Windows Runtime boundary
Filling in some of the implicit details.
How can I check whether the user has disconnected from the session?
You'll have to ask Terminal Services.
Did Windows ever find solutions for programs that crashed?
It did on occasion.
What are the requirements for the built-in Windows 10 camera-based barcode scanner?
Basically, it needs to be able to get a good picture.
Disk and File I/O performance with ETW traces: Miscellany
A few other columns.
Disk and File I/O performance with ETW traces: Why is System doing so much stuff?
The System does many things, or at least many things are blamed on it.
Preliminary notes on analyzing Disk and File I/O performance with ETW traces
Deciphering the numbers.
Why does the disk optimizer put boot files at low-numbered sectors?
Taking advantage of disk geometry.
Virtual desktops are an end-user window management feature, not a programmatic one
It's for users to organize their windows, not for programs to organize them.
How thread-safe is the Windows Runtime PropertySet object?
It's thread-safe as far as it goes, but you may want to go further.
Other uses for the -library flag of the C++/WinRT compiler
Injecting a little something extra.
On combining static libraries that implement C++/WinRT activatable objects
Separating the shared names, so you can combine them yourself.
One senior executive’s warning about escalating conflicts to upper management
You're not gonna like what you get.
Why does my command line redirection echo with an extra 1? Who’s inserting these rogue 1s everywhere?
It just came out of nowhere, or did it?
The history of the EncodePointer function for obfuscating pointers
Still useful, but less painful.
Destructing outside the lock when removing items from C++ standard containers
Managing the order of destruction.
My strategy for playing Settlers of Catan
It doesn't work, but I use it anyway.
The hidden callout: The destructor
You may not know where that's going to lead.
The prank cursor that resulted in an employee being fired before they even started
Don't try this at home.
Why aren’t my custom backgrounds, animations, and colors working, such as ApplicationViewTitleBar colors?
You're subject to user and system policy.
How do I save a C++/WinRT array_view as a com_array?
There's a not-entirely-obvious constructor for that.
What’s the point of APTTYPE_CURRENT? I mean, of course I’m current.
No matter where you go, there you are.
What is the format of the data in the AudioBuffer memory buffer, and how do I convert it to something else?
It's a bunch of floating point samples, in a particular order.
The Settings app lets me pick a custom color for my mouse pointer, how do I get in on that action?
You'll have to build a better mouse pointer.
How can I ask the networking stack whether the system has obtained network connectivity?
Depends what kind of connectivity you're looking for.
Why am I getting an access violation trying to access a method on my C++/WinRT object?
The method vanishes.
Do any Windows Runtime projections cache nondefault Windows Runtime interfaces?
Possibly, but I know two that definitely don't.
Windows Runtime objects are represented by their default interface, so choose your default interface wisely
The choice is usually obvious, but on occasion, the non-obvious choice may be better.
The BurgerMaster segment may have been legendary, but some legends aren’t true
Just give them a call.
I told the Microsoft Visual C++ compiler not to generate AVX instructions, but it did it anyway!
Well, you explicitly generate them.
How can I tell whether a file is on an SSD?
Putting the pieces together.
Taking a shortcut: You can query properties from a volume, and it will forward to the physical drive
Saving a little extra trip.
How do I get from a volume to the physical disk that holds it?
Another step down the hierarchy.
How do I get from a file path to the volume that holds it?
Walking down the topology, with a little backslash weirdness thrown in.
Mount points, volumes, and physical drives, oh my!
Navigating the storage topology.
Structured binding in C++/WinRT: The key-value pair
Taking them apart in a simpler way.
How to add C++ structured binding support to your own types
Joining the cool kids.
A brief introduction to C++ structured binding
Just learning the basics.
Just for fun: Retail demo user names in Windows 10
A bunch of plausible but fictitious names.
In 1979, some software company in Bellevue was hiring
Digging through the archives.
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
To be a leader, others must follow.
An iterable of iterables: C# collections support covariance, but C++ collections do not
You have to say exactly what you want, which may not be exactly what you have.
Error C3867: non-standard syntax; use ‘&’ to create a pointer to member: What it means and how to fix it
The compiler is trying to guess what you are trying to do. It sometimes guesses wrong.
How to plug in your USB Type A connector correctly the first time
Mating rituals.
How can I bulk-revert a subdirectory of a repo to an earlier commit?
Read it into the index.
Little gotcha with C++/WinRT iterators: The case of the mutated temporary
You are operating on copies, not the originals.
Bonus operations for C++/WinRT iterators: The IIterable<T>, and C++/WinRT collections
Stepping through a collection.
Bonus operations for C++/WinRT iterators: The IIterator<T>
The equivalent of an input iterator.
How did we end up parsing Savvyday 29 Oatmeal 94 as Saturday 29 October 1994?
Unsophisticated pattern matching.
git commit-tree parlor tricks, Part 9: How can I bulk-revert an entire repo to an earlier commit?
Take me back to a simpler time.
Structured binding may be the new hotness, but we’ll always have std::tie
Sometimes the old things are what you need.
Inside C++/WinRT: How does C++/WinRT represent ABI types?
Hiding in the internal <CODE>impl::abi</CODE> template.
How to get your C++/WinRT asynchronous operations to respond more quickly to cancellation, part 3
Automatic cancellation propagation is here.
Why does the Disk Cleanup tool’s Windows Update Cleanup take so long and consume so much CPU?
It's doing some real work.
Git commit-tree parlor tricks, Part 8: I just rebased my branch, but now I realize that I should have merged
You can rewrite the tree while preserving files.
I get a weird error about no matching function when I try to use winrt::capture
The confusing error message strikes again.
The C++/WinRT “capture” function helps you interoperate with the COM ABI world
Simplifying a common COM pattern.
Why did I lose the ability to co_await a std::future and concurrency::task?
Early moves in a direction that didn't pan out.
Embarrassing product names averted: Windows Embedded POS and Windows 10 for Advanced PCs
If you see something, say something.
What’s up with error C4838: a WinRT type cannot be a member of a union, and how can I work around it?
A restriction left over from C++03.
The macros for declaring COM interfaces, revisited: C++ implementation
Now to make things concrete.
The macros for declaring COM interfaces, revisited: C++ version
Apparently there's this new language people are using nowadays.
The macros for declaring COM interfaces, revisited: C version
Following the expansion.
How is it possible to jam a virtual card reader?
Did you feed it a bent virtual card?
This is definitely rare: It happens only ten times a month
Playing the bigger fool.
C++/WinRT injects additional constructors into each runtime class
For dealing with the objects as the smart pointers they actually are.
Rough edges in the when_all coroutine, part 2: Overloaded comma operator
Shame on you.
Rough edges in the when_all coroutine, part 1: Empty parameter list
I've got plenty of nothing.
Synthesizing a when_all coroutine from pieces you already have
You just need to await on all of them.
More on trivial functions like CopyRect and EqualRect
Let's go code golfing.
Is there a code page that matches ASCII and can round trip arbitrary bytes through Unicode?
For round-tripping binary data.
How do I convert from the C++/WinRT projection type to the C++/WinRT implementation type?
You have to trust what's inside the box.
How do I convert from the C++/WinRT implementation type to the C++/WinRT projection type?
Fortunately, there's a conversion for that.
Why are some system functions exported as stubs instead as forwarders?
Compatibility, of course, at least for some of them.
That time Bill Gates went through a McDonalds drive-through with no cash
No special treatment, not even for the richest man in the world.
How can I get the number of processors in the system, when there are more than 64?
You can ask for the active processor count.
Recognizing different types of exception objects that Windows platform libraries can throw
Just a few of the more common ones.
Inside the Microsoft STL: The std::exception_ptr
Digging inside, for debugging purposes.
On using FILE_FLAG_WRITE_THROUGH and FILE_FLAG_NO_BUFFERING for memory-mapped files
You're trying to control I/O you didn't issue.
What are the possible Status values for Win32_ComputerSystem?
There's really only one possible status.
How WRL squeezes a weak reference and a reference count into a single integer
It's basically a union of a pointer and an integer.
The case of Explorer calling into an unloaded DLL while trying to run down a reference to it
Let's do some debugging.
Working around the requirement that Concurrency Runtime task results must be default-constructible and copyable
Applying tricks to avoid the pitfalls.
Hidden constraints on the result type in Concurrency Runtime tasks
If you are using the Concurrency Runtime to represent asynchronous activity, there are some hidden constraints on the type . If you violate these constraints, the compiler will complain, but perhaps not in an obvious way.¹ If you try to create a where does not have a public default constructor, then you get an error like And if the is not copyable, then you get something like What's going on? Let's look at the copyability first. Task results must be copyable because the task result can be consumed multiple times in multiple ways. You can multiple times, and each time returns the task result. You can...
Microspeak: Placemat
Everything in its place.
How can I tell whether the user has disabled toast notifications for my app?
The ToastNotifier settings will tell you.
How do I make my accelerators apply only when used in the main window and not when the user is using a modeless dialog?
Sometimes you feel like an accelerator table, sometimes you don't.
What was so horrible about the FORMAT_MESSAGE_ALLOCATE_BUFFER flag that the Windows Store disallowed it for so long?
Letting in the riffraff.
What does it mean when it says that FORMAT_MESSAGE_ALLOCATE_BUFFER can be used in Store apps starting in Windows 10?
What happens if you use it anyway?
How can CharUpper and CharLower guarantee that the uppercase version of a string is the same length as the lowercase version?
Does it have a special under-the-table deal with the Unicode Consortium?
Peeking inside the implementation of AnsiUpper and AnsiLower in Windows 1.0
Some retro-reverse-engineering and the weird micro-optimizations.
What does the /ALTERNATENAME linker switch do?
In case of emergency, go look for something else.
What’s the deal with OLDNAMES.LIB?
For backward compatibility with pre-standard C.
C++/WinRT gotcha: Setting properties incorrectly
A bit too much search/replace during porting.
A look back at memory models in 16-bit MS-DOS
Ways of dealing with the fractured address space.
How do I set multiple items to a Windows Runtime vector in a single call?
It depends on the language projection.
C++/WinRT doesn’t let your coroutine cheat death, but it does get to say good-bye
Some manual cleanup.
How to get your C++/WinRT asynchronous operations to respond more quickly to cancellation, part 2
You can also take more proactive steps.
How to get your C++/WinRT asynchronous operations to respond more quickly to cancellation, part 1
Well, one way is to poll for it.
Deconstructing function pointers in a C++ template, returning to enable_if
Going back to the old standby to filter out unwanted specializations.
Deconstructing function pointers in a C++ template, addressing the calling convention conundrum
Finding a template metaprogramming trick that works.
Deconstructing function pointers in a C++ template, trying to address the calling convention conundrum
Hunting for the right template metaprogramming trick.
Deconstructing function pointers in a C++ template, the calling convention conundrum
Teasing out the calling convention from a function pointer.
Deconstructing function pointers in a C++ template, vexing variadics
Yet another function signature to specialize.
Deconstructing function pointers in a C++ template, the noexcept complication
Trying to infer the noexcept qualifier.
Deconstructing function pointers in a C++ template
Learning the magic incantation.
Cancelling a Windows Runtime asynchronous operation, part 8: C++/WinRT, revised
Using the completion result.
Cancelling a Windows Runtime asynchronous operation, part 7: WRL-generated asynchronous operations
The library that came before.
Cancelling a Windows Runtime asynchronous operation, part 6: C++/WinRT-generated asynchronous operations
It came from inside the building.
Cancelling a Windows Runtime asynchronous operation, part 5: C++/WinRT
Relying on the ABI result.
Cancelling a Windows Runtime asynchronous operation, part 4: C++/CX with PPL, coroutine style with raw IAsyncAction and IAsyncOperation
Looks the same, but actually tastes completely different.
Cancelling a Windows Runtime asynchronous operation, part 3: C++/CX with PPL, coroutine style
Same wrapper, different sugar.
Cancelling a Windows Runtime asynchronous operation, part 2: C++/CX with PPL, explicit continuation style
Going through a different wrapper.
Cancelling a Windows Runtime asynchronous operation, part 1: C#
How is the cancellation reported?
2020 mid-year link clearance
Another midpoint.
Mundane std::tuple tricks: Finding a type in a tuple
Inverting <CODE>tuple_element_t</CODE>.
Mundane std::tuple tricks: Creating more interesting index sequences
Generalizing our manipulations so far.
Mundane std::tuple tricks: Creating interesting index sequences
Building our own little template language.
Mundane std::tuple tricks: Selecting via an index sequence, part 2
Preserving references.
Mundane std::tuple tricks: Selecting via an index sequence
It all comes down to the index sequence.
Mundane std::tuple tricks: Getting started
Concatenating tuples the hard way, and the easy way (or maybe it's the lazy way).
Understanding warning C4265: class has virtual functions, but destructor is not virtual, part 2
Applying what we've learned.
Understanding warning C4265: class has virtual functions, but destructor is not virtual, part 1
What's it trying to warn you about? Does it matter?
Blaming the operating system for allowing people to create files with unusual characters in their names
Four fingers pointing back at your self.
Excuse me, has anybody seen the FOCAL interpreter?
I thought <I>you</I> had it.
Error 0x80131040 “The located assembly’s manifest definition does not match the assembly reference” when I use a Windows Runtime class written in C# from my C++/WinRT project
Version numbers strike again.
Using fibers to expand a thread’s stack at runtime, part 6
Caching fibers to avoid bouncing.
Using fibers to expand a thread’s stack at runtime, part 5
Expanding only as needed.
Determining approximately how much stack space is available, part 2
Probing the stack limits.
Determining approximately how much stack space is available, part 1
Ask for the memory and give it back right away.
Comparing fibers to threads for the purpose of expanding a thread’s stack at runtime
Pros and cons.
Using fibers to expand a thread’s stack at runtime, part 4
Moving an exception from a fiber to the main thead.
Using fibers to expand a thread’s stack at runtime, part 3
Propagating additional thread state.
Using fibers to expand a thread’s stack at runtime, part 2
Reducing code size with type erasure.
Using fibers to expand a thread’s stack at runtime, part 1
The simple return value.
How can I expand my thread’s stack at runtime?
You can use fibers, but you need to use them carefully.
Hiding C++ template parameter packs in a tuple
So you can pull them back out.
Template metaprogramming trick: Get the compiler to tell you what type you have
Let the error message tell you.
The SetClientGuid method of the common file and folder dialogs lets you give names to those dialogs, too
Sort of like Bob and Carol for Win32.
When programs assume that the system will never change, episode 1, redux
It was never yours to begin with.
The SettingsIdentifier property of the various file pickers lets you give names to your pickers
Like Bob or Carol?
On the various ways of constructing a C++/WinRT com_array
Surveying the constructors.
A noinline inline function? What sorcery is this?
Two different senses of the word inline.
The case of the SHGetFolderPath(CSIDL_COMMON_DOCUMENTS) that returned ERROR_PATH_NOT_FOUND
Accidentally reconfiguring the system.
How can I view my devices based on how they are connected to each other?
You can view by connection.
Reporting on what you could do once you get to the other side of the airtight hatchway
Counting all those chickens.
Storing a non-capturing lambda in a generic object
Reimplementing a small corner of <CODE>std::function</CODE>.
Inside std::function, part 2: Storage optimization
Preallocating the storage yourself.
Inside std::function, part 1: The basic idea
Holding all different kinds of things.
When you start getting in-page errors on your hard drive, it’s time to go shopping for a new hard drive, redux
The click-click-click of impending doom.
Peeking inside WRL weak references
If you ever have to debug one of these things.
The C++ preprocessor doesn’t understand anything about C++, and certainly not templates
You need to help it along.
Why does RegNotifyChangeKeyValue stop notifying once the key is deleted?
Because that's the last thing a key ever does.
How can I prevent the user from using Snip and Sketch to take screen shots?
Programs can already specify that their windows should not be captured.
Why did the message on the Start menu change from Start to Ship It! for one build?
A rogue expression of mixed encouragement and impatience.
Peeking inside C++/CX weak references
If you ever have to debug one of these things.
Diagnosing a hang: Everybody stuck in WinHttpGetProxyForUrl
Putting on your thinking cap.
COM in-process DLL unloaded while trying to clean up from the destruction of the last object
Choosing the right time to bid farewell.
How can I detect that the system is no longer showing a UAC prompt?
Let's try to understand the actual problem.
When you set Windows 10 to allow only Windows Store apps, it allows them to be installed by anyone, not just the Store app
It's about the source of the program, not the delivery mechanism.
The paradoxical sense of relief when instructions to solve the problem fail at the first step
Time saved.
How do I use C++/WinRT to implement a classic COM interface that derives from another classic COM interface?
You can specialize <CODE>guid_of</CODE>.
Why does the value of my XAML Slider change when I updated its range?
Releasing the spring.
What kind of apartment is the private apartment I created via CLSID_ContextSwitcher?
ContextSwitcherIt's where you are.
Virtual desktops are a window management feature, not a performance feature
Everything runs the same as it did before.
It rather involved being on the other side of this airtight hatchway: Planting files onto a custom PATH
Adding a directory to the PATH comes with obligations.
What will be placed in the output parameter if the function fails?
Officially, it could be anything. In practice, though, there are some constraints.
Why can’t you return an IAsyncAction from a coroutine that also does a co_await?
You already returned. No take-backs.
When I ask the GetIpAddrTable function to sort the results, how are they sorted?
Nothing particularly fancy. Just plain numerical order.
If one program blocks shutdown, then all programs block shutdown
We're all in this together, as far as the Blocked Shutdown Resolver is concerned.
The type-dependent type or value that is independent of the type
To delay the evaluation until instantiation.
Creating a non-agile delegate in C++/WinRT, part 5: Waiting synchronously from a thread that may already be the right thread
You might already be there.
Creating a non-agile delegate in C++/WinRT, part 4: Waiting synchronously from a background thread
Using things you already have.
Creating a non-agile delegate in C++/WinRT, part 3: The other cases and why they aren’t interesting
We handled only one case, but that's the only one worth handling.
Creating a non-agile delegate in C++/WinRT, part 2: The synchronous coroutine
It awaits without waiting.
Creating a non-agile delegate in C++/WinRT, part 1: Initial plunge
Forcing the delegate to run in a specific apartment.
An observation about what people used iPads for in the early days
Does everything you need, if you also bring an assistant.
Error compiling C++/WinRT runtime class: function does not take N arguments
You need to cover all the overloads.
Pulling sleight of hand tricks in a security vulnerability report, or maybe it was a prank
Something up my sleeve.
Why am I ignoring my second monitor? A case study in working from home.
Settling into the new routine has its rough spots.
A sneaky way to make sure nobody assigns test failures to your team
Buffer overflow.
Are Windows Runtime asynchronous operations guaranteed to complete?
As much as anything is guaranteed to complete.
If you say that your minimum requirements are the Universal contract, then you need to probe for anything beyond that
Reaching beyond your declaration.
How can I check whether a Windows Runtime object supports a member before I try to use it?
You can sniff at the metadata.
Accessing a member of a Windows Runtime class raises an InvalidCastException / throws a hresult_no_interface, what does this mean?
It's interfaces under the hood.
Why not just share a single event across all critical section?
How will you know when the thundering herd has calmed down?
The security check happens at the acquisition of the handle
Once you buy a handle, it's yours to keep.
Further refinements to the attempt to create a type-dependent expression that is always false
It still falls down, but for stranger reasons.
It rather involved being on the other side of this airtight hatchway: Booting into another operating system
It's not your computer any more.
We called it RAID because it kills bugs dead
The history of defect tracking databases in Windows.
The Windows Runtime IDL compiler lets you abbreviate some interface names
But only a few of them.
Providing a better error message when someone tries to use std::vector<bool> as a buffer
Defer the problem further.
Of what use is a type-dependent expression that is always false?
Deferring an assertion to instantiation.
How can I create a type-dependent expression that is always false?
Use information that you know to be true (or false).
The sad but short story of the SM_AccessoriesName registry value
Another victim of programs that reach into undocumented sections of the registry.
Why does MS-DOS put an int 20h at byte 0 of the COM file program segment?
In case you end up there, but how?
Why do people take a lock around CreateProcess calls?
Managing your inheritance.
Can I wait for a kernel event to become unsignaled?
Not directly, but maybe you can simulate it.
Meet me here on Savvyday 29 Oatmeal 94
<CODE>InternetTimeToSystemTime</CODE> tries really hard to make sense out of that sentence.
The only thing preventing them from going home was two AA batteries
I wonder where we can find them.
How can I detect that my window has been suppressed from the screen by the shell?
Cloak and dagger, without the dagger.
Should there be a standard C++ pattern for this? transform_to
Or maybe you should expect to write it out the slow way.
How to save a lot of money on cable car tickets in San Francisco
Go downstairs and buy it from the machine.
How can I configure my Windows NT service to autostart when the system gains Internet access?
You can ask to be started when the system gets an IP address.
What’s up with the CF_SYLK and CF_DIF clipboard formats?
From a galaxy far, far away.
The custom-made computers powered by pepperoni pizza
Once more for old time's sake.
The 2020/2021 Seattle Symphony subscription season at a glance
The pocket reference guide for 2020/2021.
Why are there trivial functions like CopyRect and EqualRect?
You could call them to save a dozen bytes!
Why you might need additional control over the secret event hiding inside the file object
Sometimes every little bit of contention means a lot.
If you’re not keeping the parameter, then you still want to have separate T const& and T&& overloads
Forwarding it onward.
If you plan on keeping the parameter anyway, then there’s no need to have separate T const& and T&& overloads
You can just take it by value and move it out.
Microspeak: Click stop
A place to pause and refresh.
Gotcha: A threadpool periodic timer will not wait for the previous tick to complete
Don't be like Lucy in the chocolate factory.
Quality updates: Consequences for rogue-patched binaries
You can't get back any more.
Survey of Windows update formats: The Quality update, which obsoletes all the others
Supports everything the others do, at a fraction of the price.
Survey of Windows update formats: The Express update
It's faster in some ways, slower in others.
Survey of Windows update formats: The Delta update
Trying to do some trimming.
Survey of Windows update formats: The Full update
First we need to understand where we started.
Psychic debugging: Why does my app sometimes fail to change the display settings?
Maybe you're in the box.
Why does my C++/WinRT project get errors of the form “abi<…>::… is abstract see reference to producer<…>“?
Nobody said how to produce the interface.
The various patterns for passing C-style arrays across the Windows Runtime ABI boundary
It's not an object, but not a scalar either.
The legend of the library that caused Building 4 to sink
Are the rumors true? We'll let you decide.
It rather involved being on the other side of this airtight hatchway: Disclosure of information you already had access to
A peek behind your own curtain.
The XAML hat rule: Understanding how it works and why it doesn’t
Finding the point in the parsing where the rule kicks in.
Why am I getting an exception from the thread pool during process shutdown?
The thread pool is already gone. You can't schedule any work on it any more.
Crashing in COM after I call CoUninitialize, how can COM be running after it is uninitalized?
Mind your destructors.
You might call it a “cross”, but I’m still going to call it an “X”
Different usage on this side of the pond.
How do you pronounce WinDbg?
Just a lot of hot air.
Is there a difference between creating a null pen with CreatePen and just using the stock null pen?
All null pens are functionally equivalent, so why have more than one? Are some pens more null than others?
Peeking inside C++/CX delegates
If you ever have to debug one of these things.
Windows Runtime delegates and object lifetime in C++/CX, redux
If you are the one calling the delegate, you have an extra thing to worry about.
Not even getting to the airtight hatchway: Creating a process with a different parent
Fiddling a knob that isn't connected to anything.
Microspeak: Bucket bugs, bucket spray, bug spray, and failure shift
How failures in the wild get categorized by analysis.
Can shrinking a std::string throw an exception?
It depends on how you shrink it.
How can I turn a structured exception into a C++ exception without having to use /EHa, if I can constrain exactly where the structured exception is coming from?
Trying to contain the damage.
How can I handle both structured exceptions and C++ exceptions potentially coming from the same source?
Call for a translator.
Why can’t I use SHSetKnownFolderPath to change the location of FOLDERID_LocalAppData?
A acknowledgement of the reality that it not only doesn't work, but leaves the user profile corrupted.
The historical significance of the Burgermaster drive-in restaurant
You can just phone it in.
It’s not a security vulnerability that users can access files that they have access to, even if the file is a little hard to find
Perhaps it's behind a sign that says <I>Beware of the Leopard</I>.
Over-documenting TTM_RELAYEVENT and why it results in a one-second periodic timer running as long as the tooltip is visible
Too much information leads to trouble.
Tree-walking algorithms: Incrementally performing an inorder walk of a binary tree
We need to keep track of where we came from.
Tree-walking algorithms: Incrementally performing a postorder walk of an N-ary tree
This time, we report on the way back up.
Tree-walking algorithms: Incrementally performing a preorder walk of an N-ary tree
Remembering whether you were moving down or up.
Tree-walking algorithms: Incrementally enumerating leaf nodes of an N-ary tree
Stop to rest when you turn.
Anybody who writes #pragma pack(1) may as well just wear a sign on their forehead that says “I hate RISC”
Alignment as well as padding.
Why doesn’t RegSetKeySecurity propagate inheritable ACEs, but SetSecurityInfo does?
An artifact of the timeline.
Nasty gotcha: Positioning your window beneath a topmost window makes it topmost
Picking up properties unintentionally.
2019 year-end link clearance: The different kinds of DLL planting
And why most of them aren't security vulnerabilities.
How do I make a clone of a Windows Runtime vector in C++/CX?
Taking shortcuts with special constructors.
Controversial extension methods: CastTo<T> and As<T>
Reduction in eye exercises.
C++ coroutines: The problem of the DispatcherQueue task that runs too soon, part 4
You can update it a different way.
C++ coroutines: The problem of the DispatcherQueue task that runs too soon, part 3
The storage was right in front of your nose.
C++ coroutines: The problem of the DispatcherQueue task that runs too soon, part 2
Hang on a little bit longer.
C++ coroutines: The problem of the DispatcherQueue task that runs too soon, part 1
Variables disappearing out from under you.
C++ coroutines: The problem of the synchronous apartment-changing callback
Holding the caller thread hostage.
C++ coroutines: The co_await operator and the function search algorithm
At the confluence of multiple C++ features.
C++ coroutines: Defining the co_await operator
Converting an awaitable into an awaiter.
C++ coroutines: no callable ‘await_resume’ function found for type
The thing you want isn't there.
C++ coroutines: Short-circuiting suspension, part 2
Avoiding suspension entirely.
C++ coroutines: Short-circuiting suspension, part 1
Avoiding needless stack buildup.
C++ coroutines: Awaiting an IAsyncAction without preserving thread context
Another use for a custom awaiter.
C++ coroutines: Framework interop
Plays well with others.
C++ coroutines: Constructible awaitable or function returning awaitable?
Two common patterns for simple awaitable objects.
C++ coroutines: Getting started with awaitable objects
Starting our walk-around.
In C++/WinRT, what happens when I treat an IInspectable as or convert one to a bool
Much less weird than C++/CX.
In C++/CX, hat pointers are contextually convertible to bool, but you can’t always static_cast them to bool
Because C++/CX is weird like that.
Not actually crossing the airtight hatchway: Harmless out-of-bounds read that is never disclosed
There's no way to make anything bad happen, so is anything bad actually happening?
The automotive emergency kit is not a toy
Please use it only for emergencies.
When should I use delayed-marshaling when creating an agile reference?
It's a balance between doing more work now in anticipation of saving work later.
My summer vacation: The Tower of London and Kensington Palace
Doing the admissions price math.
Using contexts to return to a COM apartment later
You can go back home again.
How do you get into a context via IContextCallback::ContextCallback?
Piggybacking on the internal infrastructure.
Setting up private COM contexts to allow yourself to unload cleanly
Your private little enclave.
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
Or maybe this is subletting? Airbnb for COM apartments?
A slightly less brief introduction to COM apartments (but it’s still brief)
Managing the multithreading.
My summer vacation: Speaking German (wait, what?)
But you went to England and France.
How do I make a clone of a Windows Runtime vector in C++/WinRT?
You copy it into your own vector, but make sure you copy what you think you're copying.
Why does the Alpha AXP predict a coroutine transfer the way it does?
Working out the possibilities.
The case of the UuidCreateSequential that didn’t use the MAC address
If you want to use it, make sure it's good.
The Magical Excel 97 Far East Language Build Screwdriver™
For your magical build needs.
I set the same ACL with the GUI and with icacls, yet the results are different
Sometimes your tools lie to you.
My summer vacation: The London Eye
Round and round. We'll, really just round. No "and round".
Why does my single-threaded program have multiple threads?
They're not your threads, but they're in your process.
Can the MTA thread exit while keeping its COM class registrations alive?
You can keep the MTA alive without having to dedicate a thread.
Not even getting to the airtight hatchway: Planting files in world-writable directories
But who uses that world-writable directory?
How can I copy or move a group of files into a new folder from Explorer?
Putting together things you already have.
The curious pattern of pre-emptively rejecting the solution to your problem: Redrawing during resizing
You'll have to invalidate it, either the easy way or the hard way.
Can I force a WM_TIMER message to be generated when the timer comes due, even if the message queue is not idle?
You can ask for it explicitly.
How can I give a C++ lambda expression more than one operator()?
Wacky template games.
How can I have a C++ function that returns different types depending on what the caller wants?
Quantum superposition comes to C++.
The legend of Steve Ballmer’s rental car, the most diligent employee in the world
What a hardworking new employee that must be.
I tried to adjust the time on my alarm clock. I failed.
Now it's not even wrong twice a day.
What happened if you tried to access a network file bigger than 2GB from MS-DOS?
What a strange world you live in.
Why does my program crash if I terminate a thread that is waiting to enter a critical section? It never got the critical section, so who cares?
But we care that it's still waiting.
For one internal build, Windows 95 contained an evil message
Another prank from the user interface team.
The program “G” is preventing you from shutting down
Minding your character set.
If you suppress GDI+ background thread, then you are expected to pump messages yourself
That stuff is now happening on your thread.
Did you hear that story about Bill Gates?: A PR person’s view
They've heard them all.
Why does FormatMessage say that %0 terminates the message without a trailing newline? Is it secretly adding newlines?
Well, it's not <CODE>FormatMessage</CODE> that's adding the newline.
If you want to terminate on an unexpected exception, then don’t sniff at every exception; just let the process terminate
Get the stack before it unwinds.
Why can’t I create a “Please wait” dialog from a background thread to inform the user that the main UI thread is busy?
Reversal of fortune.
What’s the difference between the hotkeys F6 and Alt+F6?
Switching between things, but different things.
When I tell the file or folder picker that I want only file system files and folders, why does it still show virtual folders?
Because there might be a file hiding under it.
C++/WinRT implementation extension points: abi_guard, abi_enter, abi_exit, and final_release
Coming in, going out, and going away.
By Grabthar’s Hammer, it’s a Galaxy Quest documentary
The seventh best Star Trek movie.
How can I make a call into an elevated service without requiring an elevation prompt?
This is actually quite old technology.
Why do I get a winrt::hresult_no_interface exception when I try to register an auto-revoke event handler?
The necessary infrastructure isn't there.
How should I create controls on my dialog box that has a tab control?
They are siblings of the tab control, not children.
Rugby: The rules for the casual viewer
What you need to know as an observer.
A common mistake when you try to create a C++ class that wraps a window procedure: Saving the window handle too late
You need it before then.
Fibers aren’t useful for much any more; there’s just one corner of it that remains useful for a reason unrelated to fibers
A better way to clean up.
My summer vacation: London public transportation
It's easy until you try to leave town.
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?
Anywhere it's possible to put a pointer, somebody will try to put a pointer.
Kabaddi: The rules for the casual viewer
What you need to know as an observer.
A window can’t have two timers with the same ID, so how do I assign an ID that nobody else is using?
A pointer can be used like an ID.
Auctioning off the privilege of initiating the destruction of the Microsoft old campus
Emerging victorious in the bidding war.
Why does my string consist of this Korean character repeated over and over?
Decode that character to its code point.
My summer vacation: The Changing of the Guard at Buckingham Palace
Pomp and circumstance.
How do I define a UWP XAML dependency property that is a collection type?
Putting previous guidance into practice.
Odd things you find when you read the airplane safety information card
Will it float?
What if I want the default value for a XAML dependency property to be a mutable object?
Give it one, but save it for real.
My summer vacation: Watching a German movie on the plane and learning some language history
Trying to keep that part of my brain from disappearing.
The default value for a XAML dependency property should be immutable
Spooky action at a distance.
Reminiscences on 5.25″ floppy drives of the early 1980’s
Because you may have forgotten, or perhaps never knew.
Where did DirectX code names come from?
From too much pizza.
My summer vacation: Paris public transportation
Getting around is easy. Paying for it is hard.
Why does the compiler refuse to let me export my class? If I don’t export it, then the class works fine.
You forced the compiler to try to compile it.
My summer vacation: Versailles
Ostentation fatigue is a real thing.
Why does std::is_copy_constructible report that a vector of move-only objects is copy constructible?
Because it has a copy constructor, says so on the tin, even though the constructor itself doesn't compile.
My summer vacation: The Louvre Museum
Don't waste your time queueing to see the Mona Lisa.
How do I create a Windows Runtime method that accepts a lambda?
You can use a delegate as a generalized lambda.
How did MS-DOS decide that two seconds was the amount of time to keep the floppy disk cache valid?
A stopwatch and a race against time.
Stop cherry-picking, start merging, Part 11: Chasing the commit by taking a train
Let the train carry you.
Why perform all these complex git machinations when you can just tweak the command line to get what you want?
Who controls the command line?
How to duplicate a file while preserving git line history
Synthesize it in a branch via a rename.
How to split out pieces of a file while preserving git line history: The easy way with misleading commits
Anticipating the octopus.
How to split out pieces of a file while preserving git line history: The hard way with commit-tree
More commit-tree tricks.
How do I split a file into two while preserving git line history?
The octopus delivers.
My summer vacation: The Eiffel Tower
It's really tall, for one.
Another way to sort GUIDs: Java
Because it's Java.
The Turkish lira’s currency code is an unexpected source of problems with computer programmers
Following the rules for currency codes leads to a collision with popular macro.
The sad history of the MFC TRY/CATCH macros
Because standard C++ exception handling didn't exist yet.
Trying to wrangle a site visit to Paul Allen’s superyacht “Octopus”
An unsuccessful play for a site visit.
PowerShell programming puzzle: Convert snake_case to PascalCase in one line
Abusing linguistic helper functions for fun.
It rather involved being on the other side of this airtight hatchway: Guessing window procedure magic cookies
You created a very funny-looking function pointer.
Making the COM_INTERFACE_ENTRY macro better at detecting misuse
Playing around with compile-time errors.
The COM_INTERFACE_ENTRY must be a COM interface, but nobody actually checks
And if it isn't, bad things happen.
Any sufficiently advanced technology is indistinguishable from a bomb
Even though it doesn't tick. Do bombs even tick?
Silly Alexa trick: Speaking French with a horrible American accent
Asking for a repeat, but in a different speech synthesizer.
If FlushInstructionCache doesn’t do anything, why do you have to call it, revisited
The elixir of forgetfulness.
The sad history of Unicode printf-style format specifiers in Visual C++
Getting ahead of the standard, which went a different way.
What to do if you can’t get the stovetop in your London apartment to turn on
Look for an apparently-useless switch.
On resolving the type vs member conflict in C++, revisited
Filling in some gaps in the previous discussion.
The sad history of Visual Studio’s custom __if_exists keyword
When times were simpler and bytes were precious.
One byte used to cost a dollar
The cost of software distribution.
Custom-printing your own attendee pass to the Windows 95 launch
Only the highest quality forgeries will do.
The SuperH-3, part 15: Code walkthough
Taking this thing for a spin.
The SuperH-3, part 14: Patterns for function calls
Different ways of setting up a function call.
The SuperH-3, part 13: Misaligned data, and converting between signed vs unsigned values
Okay, now we're doing some programming.
The SuperH-3, part 12: Calling convention and function prologues/epilogues
A typical RISC pattern.
The SuperH-3, part 11: Atomic operations
How do you create an atomic operation when the processor doesn't support them?
The SuperH-3, part 10: Control transfer
The return of the branch delay slot.
Why is there a huge spike in cruise ship width at 32 meters?
Squeezing through tight spaces.
The SuperH-3, part 9: Constants
Squeezing constants into a tiny instruction.
The SuperH-3, part 8: Bit shifting
Sliding left and right.
The SuperH-3, part 7: Bitwise logical operations
Just the basic operations, not much fancy.
The SuperH-3, part 6: Division
And you thought multiplication was complicated.
The SuperH-3, part 5: Multiplication
Now things get more complicated.
The SuperH-3, part 4: Basic arithmetic
Basic elementary-school stuff.
How do I fill out the Canadian eTA if I have a green card with no expiration date?
Use your passport expiration date.
The SuperH-3, part 3: Status flags and miscellaneous instructions
Basically, there's only one flag.
The SuperH-3, part 2: Addressing modes
Quite a lot for a RISC.
The SuperH-3, part 1: Introduction
Digging into the dusty boxes in the closet.
How can I extract the color from a solid color GDI brush?
You can ask for the object information.
Not actually crossing the airtight hatchway: Applying per-user overrides
The user is merely attacking himself.
What about USERSEEUSERDO and GDISEEGDIDO?
Funny names for funny functions.
Why doesn’t the Programs and Features control panel show Last Used On information?
The system doesn't try to figure it out any more, because it was always a guess, and often a really bad one.
Is it a good idea to let WriteProcessMemory manage the page protection for me?
It's a courtesy, not a contractual obligation.
When it absolutely, positively has to be there for the product demo overnight
We can make up the time in the air.
Why do pinned apps sometimes go to the end of the taskbar, rather than going into the “pinned apps” section of the taskbar?
That's not really a "pinned apps" section. It just looks like one.
Adventures in application compatibility: Calling an internal function
Clearly wandering into unsupported implementation details.
How can I log users off after a period of inactivity, rather than merely locking the workstation? Is there a “logoff” screen saver?
Putting together some building blocks.
What was the code name for Windows 7?
Windows 7.
Providing a small amount of additional control over what happens when an asynchronous I/O completes synchronously
An option named with kernel-colored glasses.
Brännboll: The rules for the casual viewer
The minimum you need to know.
After I made my DLL delay-load another DLL, my DLL has started crashing in its process detach code
You started without it. You should be able to finish without it.
Apollo 11 in real time: Follow the lunar landing mission as it happened
A fifty-year-old replay.
Windows NT services are assigned a SID based on an SHA-1 hash, but what about the risk of collision?
Those collisions are going to be hard to manufacture.
That time Dana Carvey went off script at the Microsoft Company Meeting
Timing is important in investing as well as comedy.
Cricket: The practical exam for 2019
How much did you understand the rules?
My initial confusion when encountering functions whose names begin with Co
We aren't in the math department any more.
Detecting in C++ whether a type is defined, part 5: Augmenting the basic pattern
Making things more convenient for specific scenarios.
Pesäpallo: The rules for the casual viewer
I wonder how much of this I got right.
Detecting in C++ whether a type is defined, part 4: Predeclaring things you want to probe
Declaring the thing whose definition you are looking for.
Detecting in C++ whether a type is defined, part 3: SFINAE and incomplete types
You can give something a name without saying what it is.
Detecting in C++ whether a type is defined, part 2: Giving it a special name
Maybe it's the real thing, makybe it's a fake.
A difference between cricket and baseball that most people don’t mention
The pitch invasion.
Detecting in C++ whether a type is defined, part 1: The initial plunge
Let's play games with unqualified name lookup.
I set the OFN_NONETWORKBUTTON option in the OPENFILENAME structure, but it has no effect on the network item in the navigation pane
But hey, at least it's not a button.
Baseball: The rules for the casual viewer
The minimum you need to know.
Generating good error messages from code analysis tools is harder than it looks
Describing the problem accurately, with enough diagnostics to chase the problem
Why does my attempt to index a collection with the x:Bind markup extension keep telling me I have an invalid binding path due to an unexpected array indexer?
Important detail stated by omission.
Cricket: The rules for the casual viewer
The minimum you need to know.
Microspeak: Ingestion
Let's hope it goes down easily.
A program to detect mojibake that results from a UTF-8-encoded file being misinterpreted as code page 1252
Because it happens.
2019 mid-year link clearance
Another checkpoint reached.
Why does the GetVersion function report the major version in the low-order byte, and the minor version in the high-order byte?
It seemed like a good idea at the time.
Why does Windows list my SSD system drive as removable?
Because the driver said it was removable.
Why was Windows for Workgroups pejoratively nicknamed Windows for Warehouses?
That's where most of the copies ended up, at least at first.
Detecting whether the -opt flag was passed to cppwinrt.exe: Using __has_include
Looking in the cushions of the couch.
The 2019 Microsoft Giving Campaign Run/Walk comes with some ground rules
Each rule has a story.
Getting a value from a std::variant that matches the type fetched from another variant
A bunch of type fiddling, but you'll get there eventually.
How do I write a function that accepts any type of standard container?
There's the standard way, and then there's the generous way.
What is WofCompressedData? Does WOF mean that Windows is a dog?
It stands for Windows Overlay Filter, but that name doesn't really tell you much.
A simple workaround for the fact that std::equal takes its predicate by value
Pass something else that is easy to copy.
Why does SetFocus fail without telling me why?
If you're going to replace part of the operating system, you have to replace the side effects, too.
What should you do if somebody passes a null pointer for a parameter that should never be null? What if it’s a Windows Runtime class?
They messed up, so make them suffer the consequences, but make the consequences diagnosable.
If you can use GUIDs to reference files, why not use them to remember “recently used” files so they can survive renames and moves?
Because the file that you think is the same file may not actually be the same file.
What order do the items in the “New” menu appear? It looks kind of random.
It's alphabetical order, but not in the obvious way.
How can I determine in a C++ header file whether C++/CX is enabled? How about C++/WinRT?
For conditionally enabling features, say.
The Resource Compiler defaults to CP_ACP, even in the face of subtle hints that the file is UTF-8
Subtlety is not its strong point.
Why does my C++/WinRT project get errors of the form "Unresolved external symbol void* __cdecl winrt_make_YourNamespace_YourClass(void) "?
You enabled optimizations, but there's some extra bookkeeping to support those optimizations.
Why does my C++/WinRT project get errors of the form ‘winrt::impl::produce<D, I>‘: cannot instantiate abstract class, missing method GetBindingConnector
The header file requirement was always present, but you often got away with omitting it. Not so much any more.
In the file copy conflict dialog, what happened to the option to copy the new file with a numeric suffix?
It's still there, but you have to dig a little deeper for it.
A bug so cool that the development team was reluctant to fix it
A nice parlor trick, if you had the memory for it.
I called AdjustTokenPrivileges, but I was still told that a necessary privilege was not held
Which token did you adjust?
Why does my C++/WinRT project get errors of the form “consume_Something: function that returns ‘auto’ cannot be used before it is defined”?
Narrowing down the source of the missing header file.
Why does my C++/WinRT project get errors of the form “unresolved external symbol … consume_Something”?
Declared but not defined, but what exactly wasn't defined?
In times of uncertainty, take your cue from the janitor
He's been there before.
Why does Explorer’s New menu take so long to appear the first time I open it?
It's trying to figure out what new things it can do.
Programming puzzle: Creating a map of command handlers given only the function pointer
Creating the magic decoder ring automatically.
Windows Runtime delegates and object lifetime in C++/WinRT
So many choices.
Windows Runtime delegates and object lifetime in C++/CX
You specify the lifetime rules, typically weak.
Windows Runtime delegates and object lifetime in C# and other GC languages
You've left the comfort of the CLR.
The secret signal that tells Windows Runtime events that the event recipient no longer exists
Watch out that you don't make the signal by mistake.
If each thread’s TEB is referenced by the fs selector, does that mean that the 80386 is limited to 1024 threads?
They don't all have to be different simultaneously.
When would CopyFile succeed but produce a file filled with zeroes?
Did the bytes actually make it to the disk?
Why are Bluetooth functions exported from the infrared control panel?
Artifacts of service pack constraints from long ago.
Mundane git commit-tree tricks, Part 7: Combining more than two files into one while preserving line history, manual octopus merging
Sometimes you just have to take things into your own hands.
Mundane git tricks: Combining two files into one while preserving line history
Starting with the two-file case.
Mundane git commit-tree tricks, Part 6: Resetting by reusing an earlier tree
Just take me back.
Mundane git commit-tree tricks, Part 5: Squashing without git rebase
Working completely from trees.
Mundane git commit-tree tricks, Part 4: Changing a squash to a merge
Retroactively removing a command line switch.
Mundane git commit-tree tricks, Part 3: Building a throwaway commit in order to perform a combined cherry-pick-squash
You can create a commit just so you can pick it.
Mundane git commit-tree tricks, Part 2: Building a merge commit manually out of a tree
A variation on a theme.
Mundane git commit-tree tricks, Part 1: Building a commit manually out of a tree
A little bit of plumbing.
Async-Async: Consequences for exceptions
The exception doesn't pop out until later.
Async-Async: Consequences for ordering of multiple calls in flight simultaneously
You don't know when they'll reach the other side.
Async-Async: Consequences for parameters to parallel asynchronous calls
Keep those parameter stable.
Async-Async: Reducing the chattiness of cross-thread asynchronous operations
Setting up fakes on both sides.
Spotting problems with destructors for C++ temporaries
It's sometimes later than you want.
How many ways are there to sort GUIDs? How much time do you have?
Look at all the pretty snowflakes.
How can I launch an unelevated process from my elevated process, redux
You can ask to execute it as if had been executed by somebody else.
The administrative assistant who lasted only one day: A legendary prank from days of yore
When you need to execute a prank effectively, hire a professional.
Why was Texas Hold ‘Em Poker a Windows Ultimate Extra instead of a built-in game?
Cultural sensitivity.
A little program to look for files with inconsistent line endings
Something I wrote.
On resolving the type vs member conflict in C++: The Color Color problem
You have to nudge the compiler in the right direction.
How arbitrary is the ArbitraryUserPointer in the TEB?
Another identifier defined with kernel-colored glasses.
What does this strange value for “Percent CPU” mean in Performance Monitor?
It's the percent CPU, but you have to undo the various adjustments you requested.
Microspeak: Occupant compression
Ouch, it hurts when you squeeze me there.
Today is tax day, but it’s also division meeting day, so let’s get you some forms to fill out
Render unto Caesar, but ask for a little more time.
How can a desktop app use a Windows Runtime object that infers UI context from its thread? The IInitializeWithWindow pattern
Explicitly associating with a window handle.
How can I determine the reason why my window is closing?
Listen for signals.
Even if you open a file with GUID, you can still get its name, or at least one of its names
GetFinalPathByHandle works even for files opened by ID.
When I select multiple files in the File Open dialog, why does the last item come first?
Because it's the focus.
Optimizing your cafeteria meal card stockpile
What's the rate of return on Microsoft cafeteria meal cards?
What does it mean when my attempt to stop a Windows NT service fails with ERROR_BROKEN_PIPE?
The Service Control Manager lost contact with the service, but why?
Why do we need atomic operations on the 80386, if it doesn’t support symmetric multiprocessing anyway?
You might race with yourself.
Dubious security vulnerability: Code execution via LNK file
The hard part is getting them to execute it in the first place.
On the bogosity of speculation: Guessing the price of the original Surface
Scraping the barrel.
Oh no, it’s inspection time again
Great moments in history.
C++/WinRT envy: Bringing thread switching tasks to C# (WPF and WinForms edition)
More magic tasks that break out of the thread configuration mold.
C++/WinRT envy: Bringing thread switching tasks to C# (UWP edition)
Magic tasks that break out of the thread configuration mold.
How do I wait for the completion of the delegate I passed to CoreDispatcher.RunAsync and ThreadPool.RunAsync?
You'll need your own signal.
When do CoreDispatcher.RunAsync and ThreadPool.RunAsync actions complete?
When the delegate returns, not when it completes.
What does the N in nmake stand for?
It's old now, but at the time, it was new.
Vintage Computer Festival Pacific Northwest 2019
For all your retro-computing gawking.
Turning anything into a fire-and-forget coroutine
Turning on the metaprogramming.
Expressing fire-and-forget coroutines more explicitly, -or- How to turn any coroutine into fire-and-forget
Putting it at the call site instead of in the function itself.
winrt::fire_and_forget was too forgetful
Usually, you don't care when it finishes, as long as it does.
Why does my app’s uninstaller disappear from the Start menu?
Keeping things tidy.
How do I design a class so that methods must be called in a certain order?
Consider it a chain of operation objects.
How can we use IsBadWritePtr to fix a buffer overflow, if IsBadWritePtr is itself bad?
Don't catch the overflow as it happens. Stop the overflow before it happens.
Resolving security issues sometimes involves its own degree of managing people’s egos
It's not purely technical. There's sociology here, too.
Welcome to my new home on the Microsoft Developer Tools and Services blog site
Pardon the dust.
Why is there a limit of 15 shell icon overlays?
Ran out of bits.
Asking for clear written documentation that “Require trusted path for credential entry” is no longer recommended
It was never recommended in the first place.
Precision questioning: The cynical description
Just keep digging.
Even if your assembly language code doesn’t call any Windows APIs, you still have to follow the ABI
You're not off by yourself; you're part of a society.
What order are pages in a memory-mapped file flushed out to disk?
There isn't one.
How do I destruct an object that keeps a reference to itself, because that reference prevents the object from being destructed
Keep a reference to the right thing.
Predator-prey reversal: Rock lobsters vs whelks on Malgas Island and Marcus Island
Multiple stable configurations.
Alternate definitions for English words, as inferred from bug reports
Lost in translation.
My initial frustration trying to configure our internal VoIP phones that were integrated with instant messaging
A combination of settings that the feature team considered nonsensical.
How to compare two packed bitfields without having to unpack each field
The magic carry-out vector.
How should I report errors from my Windows Runtime API?
It depends on what kind of error it is.
The std::map subscript operator is a convenience, but a potentially dangerous one
It makes code easy to read, but things happen behind the scenes you may not be expecting.
How to draw a nifty text box in your email message
This one weird trick.
That time the CEO of a company complained to Congress about Windows file extensions
Four fingers pointing back.
The 2019/2020 Seattle Symphony subscription season at a glance
The pocket reference guide for 2019/2020.
How do I permit a minus sign to be entered into my edit control, but only if it’s the first character?
Check the insertion point.
How do I allow negative numbers with the ES_NUMBER edit control style?
You'll have to roll your own.
The early history of the ES_NUMBER edit control style
It's just a little style bit.
How do I convert all these strange Unicode digits into the ones I remember from Sesame Street?
Know when to fold'em.
How can I check in Win32 whether a Unicode character is any kind of digit?
Ask for its character type.
Accidentally creating a choke point for what was supposed to hand work off quickly to a background task, part 3
Keeping the MTA alive without a thread.
Accidentally creating a choke point for what was supposed to hand work off quickly to a background task, part 2
Synchronizing on the thread pool makes you wait for the thread pool.
Accidentally creating a choke point for what was supposed to hand work off quickly to a background task, part 1
A few simple decisions accumulate and interact.
The Intel 80386, part 17: Future developments
Where we went next.
The Intel 80386, part 16: Code walkthrough
Putting the information into practice.
The Intel 80386, part 15: Common compiler-generated code sequences
Recognizing the patterns.
The Intel 80386, part 14: Rescuing a stack trace after the debugger gave up when it reached an FPO function
Pretend to be the computer.
The Intel 80386, part 13: Calling conventions
A refresher course.
The Intel 80386, part 12: The stuff you don’t need to know
For completeness but not for usefulness.
The Intel 80386, part 11: The TEB
I need another register, let's see what scraps I can find.
The Intel 80386, part 10: Atomic operations and memory alignment
Not much to work from.
The Intel 80386, part 9: Stack frame instructions
For creating and tearing down stack frames.
The Intel 80386, part 8: Block operations
One of the highly specialized groups of instructions.
The Intel 80386, part 7: Conditional instructions and control transfer
Maybe yes, maybe no.
The Intel 80386, part 6: Data transfer instructions
Keeping things moving.
The Intel 80386, part 5: Logical operations
Fiddling with bits.
The Intel 80386, part 4: Arithmetic
The things that computers do.
The Intel 80386, part 3: Flags and condition codes
It's just a bunch of stuff that happened.
The Intel 80386, part 2: Memory addressing modes
Thirteen different ways to access memory.
The Intel 80386, part 1: Introduction
Hitting a bit closer to home.
How do I get the effect of C#’s async void in a C++ coroutine? Part 3: Simplifying the boilerplate
Factoring it out.
How do I get the effect of C#’s async void in a C++ coroutine? Part 2: Keeping track of the lifetimes
There are two types of lambdas you have to write, so why not write two lambdas?
How do I get the effect of C#’s async void in a C++ coroutine? Part 1: Why does the obvious solution crash?
Wrap it up, but watch out how you do it.
Don’t pass lambdas (or other multi-line entities) as parameters to macros
It makes debugging much more difficult.
Why would the incremental linker insert padding between section fragments?
So it can be incremental more easily.
Why do we even need to define a red zone? Can’t I just use my stack for anything?
I mean, it's my stack, isn't it?
Why am I getting mojibake when I try to create a window?
Look for the character set mismatch.
It rather involved being on the other side of this airtight hatchway: Messing with somebody’s registry
Getting to the other side is left as an exercise.
STATUS_STACK_BUFFER_OVERRUN doesn’t mean that there was a stack buffer overrun
It used to mean that, but now it can mean other things, too.
The GetRegionData function fails if the buffer is allocated on the stack. Is it allergic to stack memory or something?
One of the lesser-known ground rules.
A trick for keeping an object alive in a C++ lambda while still being able to use the this keyword to refer to it
Capture it twice, once for the money, and once for the show.
Why am I getting mojibake when I try to create a shell link?
Make sure the thing you ask for is the thing you want.
How can I prevent a WebView control from opening a browser window?
It will check with you first, but you have to be listening.
Why does the elevation prompt have only the wallpaper as its background?
Caught unprepared.
2018 year-end link clearance
We made it to the end!
The case of the orphaned critical section despite being managed by an RAII type
Rolling up the debugging sleeves.
SHOpenRegStream does not mix with smart pointers
Old school meets new school, again.
Don’t forget: std::pair does lexicographical ordering, so you don’t have to
Let it do the comparing.
How do I save the results of a file search in Explorer? Not the query itself, but the results
Copy them to the clipboard.
Random internal Windows terminology: IDW, Razzle, and their forgotten partners IDS and Dazzle
A peek behind the history of the terms.
On the attempts to resurrect Space Cadet Pinball
Not many options remain.
In 16-bit Windows, some per-process data structures were really per-data segment
You just have to set up a private data segment.
It rather involved being on the other side of this airtight hatchway: Hanging the loader
You're already there. No need to brag.
How come Explorer reports higher disk space used on my volume than my third party disk space tool?
It's probably in a place your tool can't see.
Not getting past the title: This is not the bug you’re looking for
The title contains the same word, but that's about the only thing that's the same.
The case of the mysterious LoadLibrary error message after signing in
A little screen shot forensics.
How can I programmatically wait until the taskbar has finished booting completely before I create my notification icon?
It will let you know.
How can I programmatically wait until the system has finished booting completely before doing my own computations?
Your observation of the system mutates the system.
Why doesn’t my lock screen image change after I replace the image file?
It got captured when it was set.
When a customer asks for something unsupported, and they promise not to get upset when it stops working, don’t believe them
Because they'll be back.
The case of the buffer overflow vulnerability that was neither a buffer overflow nor a vulnerability
Not quite knowing how assembly language works, I guess.
Xformer 10: The Atari 800 emulator has gotten a huge update
It's over 30 years old, but can still be improved, and it sure did.
How is it that WriteProcessMemory succeeds in writing to read-only memory?
Because it tries really hard.
How can dereferencing the first character of a string take longer when the string is longer? I’m looking only at the first character, which should be constant time
There's a lot hiding in that <VAR>O</VAR>.
The plural of Nexus is Nexūs, in case you cared (which you almost certainly don’t)
Only for Latin nerds.
Why can’t I close windows directly from the Alt+Tab interface in Windows Vista?
Elevation and interruption.
Choosing error codes based on a really nice #define doesn’t necessarily lead to a readable message to the user
Device not ready? What device?
Why does Clipboard.SetData put extra junk in the clipboard data? And how can I get it to stop?
Strings and things, but you need the things.
Taking advantage of the ordering guarantees of the LINQ GroupBy method
Sorting and grouping in a particular way.
What happens if I mutate a string in a p/invoke?
It seems to work, for specific meanings of "seems".
Nifty trick: Combining constructor with collection initializer
Two great tastes that work great together.
What’s up with Code Analysis rule CA2202: Do not dispose objects multiple times?
It's trying to get inside your head.
If activation of your gift card lasts more than four hours, consult a physician immediately
Is it ready yet?
The default number of threads in an I/O completion port is the number of processors, but is that logical or physical processors?
How much stuff can happen at once?
How can I make a dialog box right-to-left at runtime?
You'll have to get that style change in quickly.
Trying to allocate the same virtual address in multiple processes
But what are you going to put there?
For a brief period, the kernel tried to deal with gamma rays corrupting the processor cache
Not sure what good it does.
How do I suppress the “Did you mean to switch apps?” warning message from my XAML WebView control?
It will ask you what to do, and you can tell it to do nothing.
The Moncler 1 Pierpaolo Piccioli, your high fashion for the elegant parties that take place in a walk-in freezer
I'm sure it looks better after you unpack it from the bubble wrap.
Closing the race window between creating a suspended process and putting it in a job
Start it there from the beginning.
Songs with every other beat removed, how to make your own!
Sounds familiar, but oddly wrong.
How do I revert a control back to its default theme?
The special signal.
What’s the point of passing a never-signaled event to MsgWaitForMultipleObjects?
It's a placeholder for something that didn't need a placeholder.
Saying good-bye to the original Microsoft Redmond campus
The home of many memories, perhaps not all good ones.
The case of the System process that consumed a lot of CPU
Let's look at the performance trace.
Gotchas when using linker sections to arrange data, part 2
An unexpected null could throw the whole thing out of alignment.
Gotchas when using linker sections to arrange data, part 1
Nulls can show up in unexpected places.
Using linker segments and __declspec(allocate(…)) to arrange data in a specific order
Getting the ducks in a row, in order.
Dubious security vulnerability: A program that adds a user to the Administrators group in the usual way
This is a perfectly legitimate program.
Sure, you can implement your own cryptographic service provider for a standard algorithm, but why would you?
You are signing up for a very big world of hurt.
Why does the MonthCalendar control show the wrong week numbers in Romania?
Wrong from whose point of view?
In the state of Washington, you are allowed to turn left on a red light onto a one-way street
And freeway onramps count as one-way streets.
If the prototypes of DispatchMessageA and DispatchMessageW are identical, why have both?
Because there's still a character set dependency.
Dulce et decorum est pro patria party
Anyone up for a toga party?
What happened to the Arial Unicode MS font?
It couldn't do what it was originally created to do.
The case of the oplock deadlock poppycock
Call Sherlock.
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
A little nudging here, a little nudging there.
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
Make <I>everything</I> a multiple of five.
Adding a Ctrl+arrow accelerator for moving the trackbar by just one unit, part 2: Second try
Intercepting the thumb motion.
Adding a Ctrl+arrow accelerator for moving the trackbar by just one unit, part 1: Initial plunge
The obvious thing starts to get out of hand.
Why does the Entry Point Not Found error dialog sometimes not include the name of the missing entry point?
Because the name is too long.
File-extending writes are not always synchronous, which is entirely within the contract
It is an option but not a requirement.
After reporting a non-responsive program to Windows Error Reporting, why does the process spawn a suspended child process?
That's just a ghost, a shadow of the original.
What does the “Ae” stand for in AeDebug?
I'm not sure, but I think it's Application Error.
Why does Windows ask me to pick a program with which to open a file, even when I already specified which program I want to use to open the file?
It's just double-checking after the situation has changed.
How can I programmatically inspect and manipulate a registry hive file without mounting it?
Enter the offline registry library.
So, um, what are we looking at?
The wonders of nature, perhaps.
Why doesn’t GetTextExtentPoint return the correct extent for strings containing tabs?
It doesn't do carriage control.
How can I include/exclude specific memory blocks in user-mode crash dumps?
Add it to the inclusion or exclusion list.
Notes on DrawText and tab stops
You can ask, but then you can't ask for other things, unless you ask a different way.
The numerology of the sample directory listing in the Windows 95 font selector property sheet page
Leave a thumbprint.
When I call CryptProtectData with the same parameters, why aren’t the results identical?
A little added seasoning.
How can I use WS_CLIPCHILDREN and still be able to draw a control with a transparent background?
Removing all the barriers to painting, perhaps too many.
Can I be sure that turning on automatic generation of short file names will get me short file names?
You can try hard, but it may not succeed.
Practical example of why you need to leave room for German localization
Try to say it all in one breath.
All sorts of bad things happen when we disable the Task Scheduler service, is that bad?
Well, it sure doesn't sound good.
Generating a table with vertical text, like I did with the sad history of the C++ throw(…) exception specifier
Here's how I did it.
The sad history of the C++ throw(…) exception specifier
I promise not to throw, but who's going to check?
Can you wear wallpaper on your feet? You can if it’s a PARTY.BMP!
Wearing your history.
Considering the performance implications of converting recursion to an explicit stack
Another game of trade-offs and balances.
What does the thread parameter to SetWindowsHookEx actually mean?
What does it mean to be "associated" with a thread?
How do I prevent my program’s temporary documents from appearing in Search?
Put them in the right place.
Why does the compiler turn my conditional loop into an infinite one?
It's all in the threading.
Why is regsvr32 exiting with code 3?
Coming up with theories and ways to test those theories.
What do the various regsvr32 exit codes mean?
Reporting which step the problem occurred at.
Why did every Windows 3.0 DLL have an exported function called WEP?
The Windows Exit Procedure.
Why is Alt+F4 the hotkey for closing a window? Why not Alt+F5 or Alt+F3?
It was the next one available.
A lack of species sensitivity when serving pizza to guests
This bacon thing is getting out of hand.
What defines an old-style common dialog?
Going back into the Before Time.
Why does the Zune HD have the message “For our Princess” on the inside of the case, and why is she a princess?
A tribute to a team member who passed away.
Raising the colon off the ground
Not something your gastroenterologist says, surprisingly.
Anything is a soldering kit if you’re brave enough: The MOnSter 6502
Are you nuts? Probably.
How do I get the system to run my program in this very special way?
You can set up the special way yourself.
Le Chatelier’s principle in action: Notifications
Let me notify you about things you don't care about.
How can I conditionally compile based on a preprocessor macro value, while ensuring that the macro is correctly spelled?
Another stupid preprocessor trick.
Removing the TerminateThread from a DLL that needs to shut down a helper thread at unload
Designing it out again.
What does it mean for a window to be Unicode?
The expected character set of the current window procedure.
How do I request that my out-of-process COM server run unelevated?
Back to the interactive user.
Apparently they know more information about me than me, but dare I ask?
Blind content retweeting.
That time the Word team hired somebody who never showed up, who turned out to be an important member of the team in spite of not being on it
Well, we've got the nameplate at least.
Removing the TerminateThread from code that waits for a job object to empty
Designing it out.
The early history of Windows file attributes, and why there is a gap between System and Directory
One, two, four, sixteen.
Obsolete Microspeak: TDBN and the six-pack
Old Windows 8 terminology.
The evolution of Windows 8 charms
For regaling people at your next cocktail party, perhaps.
How do I force the Task Manager window closed whenever it opens?
Um, that's not really your decision.
The Windows 95 team were proud slackers
Another adopted slight.
The PowerPC 600 series, part 14: Code walkthrough
Putting the theory into practice.
The PowerPC 600 series, part 13: Common patterns
How to recognize different kinds of jumps and calls.
The PowerPC 600 series, part 12: Leaf functions
Making do with what you are given.
The PowerPC 600 series, part 11: Glue routines
Binding the two sides together.
The PowerPC 600 series, part 10: Passing parameters, function prologues and epilogues
The most dangerous parts of flying a function are take-off and landing.
The PowerPC 600 series, part 9: The table of contents
Finding your bearings.
The PowerPC 600 series, part 8: Control transfer
Jump around.
The PowerPC 600 series, part 7: Atomic memory access and cache coherency
How to avoid a break-up.
The PowerPC 600 series, part 6: Memory access
Load 'em up.
The PowerPC 600 series, part 5: Rotates and shifts
Get out your Swiss army knife.
The PowerPC 600 series, part 4: Bitwise operations and constants
Twiddling around.
The PowerPC 600 series, part 3: Arithmetic
Who knew there were so many ways to add numbers.
The PowerPC 600 series, part 2: Condition registers and the integer exception register
Keeping track of things that happened.
The PowerPC 600 series, part 1: Introduction
Here we go again.
A puzzle aboard the Anacortes-Sidney ferry: How do the cars get off?
At an apparent impasse.
Creating an awaitable lock for WinJS and JavaScript Promises
Rolling onward.
Creating an awaitable lock for C++ PPL tasks
Rolling our own.
Creating an apartment-aware PPL task from nothing
It says it has to be <CODE>IAsyncAction</CODE>- or <CODE>IAyncOperation<T></CODE>-derived, so let's do that.
Server names: One of the remaining places where IT managers can be a little silly
Usually by establishing a theme.
Dark Pattern: Opt-in above the fold, but opt-out below the fold
Don't stop yet. Read all the way to the end.
Is the TerminateThread function synchronous?
Nope. It merely starts the termination but does not wait for the termination to complete.
What happens to custom unhandled exception filters if a debugger is not running?
Nothing, that's what. Absolutely nothing.
Why are my file write operations synchronous, even though I opened the file as FILE_FLAG_OVERLAPPED?
FLAG_OVERLAPPEDExtending the valid bytes is always synchronous.
Pushing the boundaries of cryptography in a security vulnerability report
If it's what you say, then you don't need a supercomputer.
The heavy metal umlaut reaches baked goods
For that extra Germanic oomph.
How do I trigger an EN_UPDATE notification for all of my edit controls when the user’s locale information changes?
It's your edit control, so you can do it yourself.
How can I get the actual window procedure address and not a thunk?
Match the character set of the top-level window procedure.
When is it appropriate to use the current processor number as an optimization hint?
Try not to let it slip out from under you.
Sure I can protect data with CryptProtectData, but how do I remove the ability to decrypt it?
You can put a secret in the nonce, though it's not really a secret by that point.
What is this vmmem program that is using up all my CPU and memory?
That's where your virtual machine resource usage goes.
Internal training video on expense reports contains inconsistency: Alert the media!
Was this a test? I'm not sure.
Warning: Ruler is not to scale
Inches enlarged to show texture.
When generating a random password, the result must still be a valid string
Invalid strings can't round trip through multiple encodings.
Why does a non-recursive ReadDirectoryChangesW still report files created inside subdirectories?
Because they do affect the top-level directory.
Const methods don’t prevent a method from having side effects
Though they shouldn't if you know what's good for you, but the compiler doesn't know whether you know what's good for you.
How do I change the password of another user without having to sign in as them?
You can do it from the password change screen.
Stop merging if you need to cherry-pick
An opposing view from the VSTS team.
The case of the very large memory blocks of the same size, mostly zero, but whose nonzero bytes follow a pattern
Some initial pattern recognition, followed by an ad-hoc tool.
How can I detect whether the user is logging off?
It's hidden as a strange sort of system metric.
The Windows Calculator no longer generates tiny errors when calculating the square root of a perfect square
Tweaking the algorithm.
Did you happen to lose something in the Amstel River? Say within the past 500 years?
Maybe you can find it here.
How can I determine why the System process is listening on port 80?
netsh can tell you.
Consider the environment: Do you want a receipt?
Actually, I don't really care whether you want one. The decision is foregone.
2018 mid-year link clearance
Reaching the halfway point.
How can I detect from the preprocessor what a macro’s definition is?
Evil preprocessor tricks.
Lock free many-producer/single-consumer patterns: A work queue of distinct events, order not important, follow-up question
We try to minimize spurious wake-ups, but eliminating them is probably not worth the effort.
Taking advantage of the asymmetry of offline compression
You can spend a lot of time compressing, but decompression still needs to be fast.
The cost/benefit analysis of comparing before an assignment
Factors pull in both directions. The result is a balance.
How I learned to type
On an old manual typewriter.
What can influence how much stack is consumed when sending a message?
Who wants to know? No really, that's the answer.
When I intentionally create a stack overflow with SendMessage, why do I sometimes not get a stack overflow?
It depends on what overflows first.
Microspeak: knobs
Configuration settings, basically.
Woodworking, the opposite of software development
According to self-reported data from one person who could have just made it up.
Is there a problem with CreateRemoteThread on 64-bit systems?
There's more to injecting code than copying bytes.
How do I programmatically control the order of my program’s notification icons?
That's not something you can control programmatically.
Even though the brand is called One A Day, none of them actually should be taken one a day
For large values of one.
Why does the CREATOR_OWNER SID sometimes reset itself to the object’s current owner rather than its original owner?
It's a snapshot, but you can ask for a new snapshot.
Stupid cmd.exe tricks: Entering a directory that doesn’t exist, then immediately leaving
It's as if it never existed. Oh wait, it never existed.
Where is the Seattle BoltBus stop?
Adjacent to the Uwajimaya parking lot on 5th, at least as of this writing.
Pulling the rug out from under an internet protocol
Extracting maximum value from licensing.
Unusual choice of units: 1.8 billion square millimeters
So many yet so small.
Why does GetServiceDisplayNameA report a larger required buffer size than actually necessary?
It's making a conservative guess.
What is this weird constructory syntax C::C()?
An archaic syntax from ancient times.
The unhandled exception filter is the responsibility of the process; don’t change it without permission
It's only common courtesy.
Stupid cmd.exe tricks: Changing directories with forward slashes instead of backslashes
Provided it doesn't look like a switch.
Adventures in application compatibility: Following a detour off a cliff
An arrow pointing to nowhere.
How can I write a program that monitors another window for a title change?
Accessibility saves the day once again.
How can I obtain the heap from which a heap block was allocated?
You'll have to keep track of that yourself.
When you call OpenThreadToken while impersonating, you have to say who is asking for the thread token
I am for you.
The alphabet, in alphabetical order, in various languages
From A to Z, or beyond.
How do I get file version information from the command line?
PowerShell does for you.
How are BitBlt raster opcodes calculated?
The complicated language of raster operation codes.
My namespace importing trick imported the same three namespaces into each top-level namespace, yet it worked?
They are different namespaces, spelled the same.
How do I create a disabled checkbox for a listview item?
A little state image magic.
If you say that your buffer can hold 200 characters, then it had better hold 200 characters
Otherwise the mistake is on you.
Why does the install date and size of a program change roughly two days after I install it, even though no changes were made to the program in the meantime?
Because the system is trying to fill in missing information.
Maintaining Notepad is not a full-time job, but it’s not an empty job either
Adding features by removing code.
Misdirected security vulnerability: Malformed file results in memory corruption
Who did the corrupting?
How do I create a SAL annotation for a structure with a variable-length array?
The <CODE>_Field_size_</CODE> annotation does the trick.
C++ namespace parlor tricks
Shuffling names around.
Why is Windows Compressed Folders (Zip folders) support stuck at the turn of the century?
Because that's where we last left it.
For a brief period, Windows 95 could run Windows 3.1 in a virtual machine
The ultimate in backward compability.
Why can’t FindWindowEx find another program’s window by name?
Are you sure it's there?
On the difficulty of getting pixel-perfect layout in Win32 dialog templates
That's not what it's for.
Why does my shortcut to a nonexistent file end up with spaces changed to underscores?
Trying to make the best of a bad situation.
Microspeak: ZBB, recall class, glide path, and RTM
Bug tracking jargon.
After all, it’s called a hotkey, not a hotcharacter
Hotkeys are based on keys.
See you at Build 2018 next week
Hopping across the lake.
Avoiding deadlocks when cancelling a thread pool callback, part 2: Referring back to the containing object
Run it, but only as long as I still exist.
Avoiding deadlocks when cancelling a thread pool callback, part 1: External callback data
Breaking the deadlock by disassociating from the thread pool.
How to avoid accessing freed memory when canceling a thread pool callback
Making sure everybody is done before you free it.
Windows 10 virtual desktops are a window management feature, not a security feature
It's just for helping you focus.
The seasoned pianist’s guide to musical collaborators
What's it like working with others?
I don’t know how I managed to be presenting at the same conference as Dona Sarkar
Maybe if I hang out with her enough, some of the cool will rub off.
A cute hidden message in a image to entertain you while you wait
Pull out your handy decoder ring.
How can I have my program execute some code only if run from the Visual Studio debugger?
Let's look at the problem rather than the question.
Microspeak: Tented
No peeking into the tent.
It rather involved being on the other side of this airtight hatchway: Passing invalid parameters from kernel mode to another kernel-mode function corrupts the kernel (who knew?)
You're already deep on the other side.
The early history of redundant function pointer casts: MakeProcInstance
The generic function pointer.
The MIPS R4000, part 15: Code walkthrough
Let's look at some code.
The MIPS R4000, part 14: Common patterns
How to recognize different kinds of jumps and calls.
The MIPS R4000, part 13: Function prologues and epilogues
Keeping the unwinding bookkeeping straight.
Whoa, that fitness tracker is a really expensive watch
And you only have to recharge it every few days, instead of every two years.
The MIPS R4000, part 12: Calling convention
Pretty standard… for a MIPS.
The MIPS R4000, part 11: More on branch delay slots
I guess this really confuses people.
The MIPS R4000, part 10: Trampolines and stubs
You can't get there from here, at least not in one go.
The MIPS R4000, part 9: Branch delay slot parlor tricks
Technically legal, but strange.
The MIPS R4000, part 8: Control transfer
Branch, but wait, not quite yet.
The MIPS R4000, part 7: Memory access (atomic)
Load and lock, erm, link.
The MIPS R4000, part 6: Memory access (unaligned)
Split 'em up.
The MIPS R4000, part 5: Memory access (aligned)
Simple loads and stores.
The MIPS R4000, part 4: Constants
Load them up, a half at a time.
The MIPS R4000, part 3: Multiplication, division, and the temperamental HI and LO registers
You have to treat them nicely or they will refuse to coöperate.
The MIPS R4000, part 2: 32-bit integer calculations
The usual suspects.
The MIPS R4000, part 1: Introduction
Here we go again.
Why is it cheaper to fly out of Vancouver for spring break instead of Seattle, while also being cheaper to fly out of Seattle for spring break instead of Vancouver?
Study the school schedules.
How do I choose between the strong and weak versions of compare-exchange?
It depends on how bad a spurious failure is for your algorithm.
Geology throwdown: The whisper of the rocks
Listen or don't listen. Pick a side.
What’s up with compare_exchange_weak anyway?
It's handy for certain classes of processors.
When I memcpy a struct into a std::atomic of that struct, why does the result not match?
You're storing it wrong.
The WMI root node is just a node in the WMI namespace
Don't let the name fool you.
A rare opportunity to fact-check the “celebrity net worth” sites
Well, technically it's "north".
What are the odds that two pull requests get completed at the exact same time?
Merges do not occur instantaneously, so there is a window of opportunity for overlap.
Stop cherry-picking, start merging: Index
For one-stop reading.
Stop cherry-picking, start merging, Part 10: Web-based workflow for Azure DevOps (formerly VSTS)
Clicking your way to a merged cherry-pick.
The mystery of the stalker dental hygienist
Haven't I seen you before?
Stop cherry-picking, start merging, Part 9: Chasing the commit
Catch the train.
Stop cherry-picking, start merging, Part 8: How to merge a partial cherry-pick
Pick what you want.
Stop cherry-picking, start merging, Part 7: Preventing a change from leaving a branch
More advanced merge base tricks.
Stop cherry-picking, start merging, Part 6: Replacing the temporary fix with the permanent fix
Advanced merge base tricks.
Stop cherry-picking, start merging, Part 5: Exploiting the three-way merge
Making sure you have the correct merge base.
Stop cherry-picking, start merging, Part 4: Exploiting the recursive merge algorithm
Recursive merging for fun and profit.
Stop cherry-picking, start merging, Part 3: Avoiding problems by creating a new merge base
Move the cherry-pick into the merge base so that git knows it exists in both sides.
Stop cherry-picking, start merging, Part 2: The merge conflict that never happened (but should have)
You wish you got a merge conflict, but you didn't.
Stop cherry-picking, start merging, Part 1: The merge conflict
Setting the pieces into motion.
Torsken har ankommet
Cod you believe it?
Why is the daylight saving time cutover time 1 millisecond too soon in some time zones?
Another other time zone anomalies.
What’s the difference between CreateTimerQueueTimer and SetThreadpoolTimer?
They are both the same thing under the covers.
When MSDN says NULL, is it okay to use nullptr?
One of many equivalent formulations.
Microspeak: The triad, the ad-hoc acronyms that result, and the arithmetic problem 3 × 3
There are six possible ways of arranging them. Surely one of them must look good.
Inadvertently designing a horrible time and date picker
Perhaps inspired by the worst possible volume control.
If I call GetExitCodeThread for a thread that I know for sure has exited, why does it still say STILL_ACTIVE?
Because that's not the thread handle you think it is.
How does Task Manager choose the icon to show for a process?
It uses your window icon, and if you don't have a window, then it starts hunting.
An amusing story about a practical use of the null garbage collector
The computer itself ceases to exist.
It rather involved being on the other side of this airtight hatchway: Replacing an unsigned writable MSI package
Another case of the insecurely-configured system.
I just met you, and this is crazy, but here’s my callstack. Debug me maybe.
You gave me nothing at all, but still, you're in my way.
The 2018/2019 Seattle Symphony subscription season at a glance
The pocket reference guide for 2018/2019.
How do I make sure that my shell extension is at the top of the context menu?
The battle for absolute supremacy continues.
Why does IsPathRelative return FALSE for paths that are drive-relative?
It's complicated.
How can I call freopen but open the file with shared access instead of exclusive access?
Coming through the back way.
We couldn’t create a new partition or locate an existing one, possible workarounds
Well, it worked for me.
This is a race the display driver wouldn’t normally expect to lose
But flukes can happen.
So what is a Windows “critical process” anyway?
<CODE>IsProcessCritical</CODE> tells you whether a process is critical, but what does that mean?
Why are there two kinds of Universal Windows apps, one for Windows 8 and another for Windows 10?
Universality is not universal.
What’s the difference between the zero width non-joiner and the zero width space?
Are you separating two words?
When Windows copies a file, does it ever copy bytes that are in the slack space?
Keeping tabs on the slackers.
There are no bugs in the I/O manager
True each time it is uttered.
Optimizing BitBlt by generating code on the fly
Artisanal bit block transfers made to order.
What do the output values from CoGetApartmentType mean?
Four types of threads, possibly in the neutral apartment temporarily.
Why does misinterpreting UTF16-LE Unicode text as ANSI tend to show up as just one character?
Because you're probably working in the ASCII subset.
Microspeak: POR
The plan of record.
// If this happens, I am going to quit and become a barista
Maybe you should check if Starbucks is hiring.
The case of the SRWLock violation in a thread pool work item
Application verifier tells the story.
Spurious wake-ups in Win32 condition variables
Another peek behind the curtain.
How can I get a signature for a Windows system that will remain unchanged even if the user reinstalls Windows?
The SystemIdentification class will give you something.
Communication by hand signals, and other complex coordination problems
The secret language.
Why does hypervisor remain enabled even when Hyper-V is disabled in Windows Features?
Because somebody else needs it.
Microspeak sighting: over-index
It's like birdwatching, but for words.
Well that was a helpful error message
I guess they don't know what went wrong either.
The saga of Heartland vs. The United States Beet Sugar Association
Is molasses a foreign substance with respect to sugar?
How can I reserve a range of address space and create nonzero memory on demand when the program reads or writes a page in the range, even when multithreading?
Some memory mapping magic.
Like love, taxes make people do the strangest things
Tariff engineering.
How can I reserve a range of address space and create nonzero memory on demand when the program reads or writes a page in the range?
Swizzle me this.
How can I reserve a range of address space and receive notifications when the program first reads or writes a page in the range?
Be in the exception handler chain.
Microspeak: Impedance mismatch
Any kind of mismatch, really.
The history of change-packing tools at Microsoft (so far)
They all say "pack" for one reason or another.
A helper template function to wait for a Win32 condition variable in a loop
Another case of the spurious wake-up.
Stuff my father-in-law says: On taking the train
A five-minute tour.
A helper template function to wait for WaitOnAddress in a loop
Because this is what you always have to do.
Why does HRESULT begin with H when it’s not a handle to anything?
Well, it used to be a handle.
As far as the French government is concerned, I am the expert on Windows XP
At least it's my name on the paperwork.
How do I know that Resource Monitor isnt just retaining a handle to the terminated process?
Let's try it again, with feeling.
Why don’t context menus respect the UI state for keyboard accelerators?
Well, technically, they're a separate window.
What does it mean when the documentation says that you must specify the app in the system’s metadata before you can retrieve SmbiosInformation properties?
It's talking to a specific "you" that's not you.
Why is there a semicircular bar at the base of the ORCA card reader?
Another mystery.
How do I get the computer’s serial number? Consuming Windows Runtime classes in desktop apps, part 5: PowerShell
Now we're cooking with power.
How do I get the computer’s serial number? Consuming Windows Runtime classes in desktop apps, part 4: C#
Over into managed code.
How do I get the computer’s serial number? Consuming Windows Runtime classes in desktop apps, part 3: C++/WinRT
Getting into the modern swing of things.
How do I get the computer’s serial number? Consuming Windows Runtime classes in desktop apps, part 2: C++/CX
Annoying to set up, but easier to use.
How do I get the computer’s serial number? Consuming Windows Runtime classes in desktop apps, part 1: Raw C++
We can do this the easy way or the hard way. Let's do it the hard way.
Why are the module timestamps in Windows 10 so nonsensical?
They're really a uniqueness identifier.
What happens when a huge number of people share a single grocery store loyalty card?
They can tell.
How do I know that Resource Monitor isn’t just retaining a handle to the terminated process?
Let's run some more experiments.
2017 year-end link clearance
Another year passes.
How does Resource Monitor get information for processes that already terminated?
It's an optical illusion.
Why do I have to pass a valid page protection value to VirtualAlloc even if it ignores it?
It ignores it, after it validates it.
Microspeak: over-index
To give too much prominence to something in a discussion or analysis.
Time travel is here, at least when it comes to debugging
A present for all the developers out there.
Exposing undefined behavior when trying to port code to another platform
Oops, that wasn't allowed after all.
What’s the difference between VARIANT and VARIANTARG?
Well, is it an argument?
How do I ShellExecute a file, but with a specific program instead of the default program?
Count the ways.
How does Task Manager categorize processes as App, Background Process, or Windows Process?
It's a made-up term.
On the little-documented role of the page-turner
Intended to be invisible.
What kind of messages can a message-only window receive?
Only messages that are sent directly to that window.
Creating double-precision integer multiplication with a quad-precision result from single-precision multiplication with a double-precision result using intrinsics (part 3)
Applying the sign adjustment.
Creating double-precision integer multiplication with a quad-precision result from single-precision multiplication with a double-precision result using intrinsics (part 2)
Put it all in registers.
Creating double-precision integer multiplication with a quad-precision result from single-precision multiplication with a double-precision result using intrinsics (part 1)
Once more with intrinsics.
Why not slipstream ZDP fixes into the bits downloaded by the installer rather than being a separate download?
Well, yeah, but what if it was downloaded months ago?
Coroutines mean that the thing that looks like a stack variable may not technically be one
Hoisted into the future.
How do I respond to the WM_MENUCHAR message?
You identify the menu item that corresponds to the character.
Knowing just enough about debugging IRPs to chase the problem out of the I/O stack
Fumbling around and stumbling into a diagnosis.
How can I prevent the keyboard focus rectangle from appearing on a control I created?
You can lie to the control.
Tree view check boxes: The extended check box states
Partial, dimmed, and exclusion.
Tree view check boxes: A sordid history
How we got into the mess we did.
Creating tree view check boxes manually: Themed check boxes
Using visual styles.
Creating tree view check boxes manually: Responding to clicks
Cycling through the state images.
Creating tree view check boxes manually: A simple state image list
Rebuilding the states, maybe with some new ones.
Beware of the leaked image list when using the TVS_CHECKBOXES style
It'll make one for you, but it's still on you to destroy it.
The TVS_CHECKBOXES style is quirky, which is a polite way of saying that it is crazy
You have to set it at just the right time.
Getting a parent and child window to have the same UI states
Wrangling them into agreement.
Demonstrating what happens when a parent and child window have different UI states
Setting up for a fail.
What is the documentation for SetParent trying to tell me about synchronizing the UI state?
There's this thing called a UI state, see, and it should be synchronized.
The sad implementation history of COM component categories and why it means you have to click twice to see your newly-installed taskbar toolbar
First we have to find them.
How can I find the installation directory for my UWP application?
You can ask PowerShell.
The wrong way of benchmarking the most efficient integer comparison function
Missing the forest for the blade of grass.
Why is there no way to add a permission to a page with VirtualProtect instead of replacing it?
Who's in charge here?
What happens if you simply return from the thread callback passed to _beginthread and _beginthreadex?
Who's got the thread handle?
Microspeak: FCIB
Foreign checked-in binary, or at least that's what it means now.
On memory allocations larger than 64KB on 16-bit Windows
The mysterious __AHINCR.
Cancelling the INamespaceWalk::Walk operation a little faster
You can use <CODE>IActionProgress</CODE>
How can I cancel the INamespaceWalk::Walk operation?
You can cancel it during a <CODE>INamespaceWalkCB</CODE> callback.
How can I control which parts of the shell namespace the INamespaceWalk::Walk operation will walk into?
You can ask it to skip the folder, or you can tell it to give up entirely.
Was there a problem with Windows 95-era programs relying on undocumented information disclosure stuff?
Surprisingly not.
Why did Windows 95 store image list bitmaps four-across instead of as a strict vertical strip?
To make sure they all fit in a 16-bit coordinate space.
Why are my notification icon customizations lost after six months of disuse?
Sorry, didn't realize you were still using it.
What are the dire consequences of accessing the fields of __m128i directly?
It works, but not well.
How can I detect that a shell item refers to a virtual folder, or to a file system inside a file?
Unpacking the attributes.
Why does upgrading my project to Unicode cause Visual Studio to use a different version of the common controls?
Because it's now possible.
Should I name my file mapping after the file it was created from?
Well, it depends on why you're giving it a name at all.
How do I preserve the user’s notification icon preferences for my program after I update it?
Give it a GUID.
How do I prevent my registered hotkey from firing repeatedly due to auto-repeat?
You can ask for auto-repeat to be ignored.
Why was the Windows 95 precursor project code-named Panther abandoned?
Didn't fit in a 4-megabyte bag.
When I use Alt+PrtSc to take a screen shot of a maximized window, why does it capture a few pixels from an adjacent monitor?
Because it's hanging over the edge.
A closer look at the complexity analysis of finding the k’th smallest element in two sorted arrays
Let's calculate it properly.
On the gradual improvements in how the system deals with the failure to initialize a critical section
Gradually improve the situation until the problem vanishes completely.
How do I create a shortcut whose target is specified by a relative path?
It's already in there.
I used WS_EX_COMPOSITED to get rid of my redrawing flicker, but it resulted in sluggish response
The system needs to know when to present the back-buffer.
When a stopgap solution becomes an undocumented feature some people rely on
It was never meant to be long for this world.
Nasty gotcha: Powershell aliases that match commands you might want to run
Because two-letter names would never collide, right?
Exploring the problem: Create a file that only one process can write to
That's not the real problem.
Why does my program crash when I throw an exception from an APC?
Because c'mon.
How can I specify that my DLL should resolve a DLL dependency from the same directory that the DLL is in?
Use the manifest.
Microspeak: Gardening
General housekeeping.
Why does NTVDM create empty IO.SYS and MSDOS.SYS files?
Compatibility, of course.
How can I investigate the possibility of a lot of leaked window classes (RegisterClass)?
Looking for names.
Evaluating the security consequences of an instance of reading past the end of a buffer
In order to get the information, you must already have significant powers.
Reconciling yucky boys and gross kissing with the occasional dance
Just friends.
The Resource Compiler’s preprocessor is not the same as the C preprocessor
It's a very limited subset.
Alas, Microsoft Building 109 Conference Room A is no more
Another code word bites the dust.
How can I detect that my window is on the current virtual desktop?
And what are the recommended policies for using virtual desktops anyway?
Why does my thread handle suddenly go bad? All I did was wait on it!
The scary world of _beginthread.
CancelIoEx can cancel synchronous I/O, which is kind of nice
Get me out of there.
How to check if a pointer is in a range of memory
Thanks to the C language standard, it's trickier than it seems.
Who implemented the Windows NT blue screen of death?
My colleague John Vert.
What happens if I wake a condition variable when nobody is waiting for it? Is the wake saved for the next thread that waits?
It shouldn't matter.
What does it mean when I get an access violation at a very low address when entering a critical section?
It probably means that you're entering a critical section that is not initialized.
How accurate are the various Windows time-querying functions?
Most of them are based on the system timer, but some are better.
What is the correct way of using SaveDC and RestoreDC?
Understanding the model.
The NET HELPMSG command will decode Windows error codes, at least the simple ones
It's originally for decoding network error messages, but it doesn't actually care.
The increasingly complex Kremlinology surrounding Windows
Wait, who's standing next to whom?
How can I diagnose why my FreeLibrary isn’t freeing the library?
Application Verifier to the rescue.
Why is my window unexpectedly becoming topmost?
There are a few places where the system will auto-topmost a window.
What is the correct way of using the string buffer returned by the WindowsPreallocateStringBuffer function?
Write the characters you allocated, but only those characters.
Microspeak: Ripcord
Deploy the emergency parachute.
If you configure a program to run in Windows 2000 compatibility mode, then it is also vulnerable to Windows 2000 security issues
Bug-for-bug compatibility.
Nasty gotcha: SetThreadUILanguage cannot be used to restore the thread UI language
You have to use some other function entirely.
What are anonymous structs, and more importantly, how do I tell windows.h to stop using them?
The struct with no name.
Can I enable Large Address Awareness dynamically at runtime?
No, but you can maybe fake it.
Does anybody know what really happened on August 25, 2017 at the Red Sox/Orioles game?
A strange thing might have happened, but did it?
Why did my systems reboot into the Recovery Environment and how do I prevent that from happening in the future?
You can disable it in the boot configuration.
Inadvertently becoming the change you wish to see in the world
Sharing some duties.
I guess I may as well confess that I wrote the Itanium information in the Debugging Tools for Windows package
The story of how I ended up being the guy who understands all these processors.
The Alpha AXP, epilogue: A correction about file system compression on the Alpha AXP
Setting the record straight, even though the lie has already circumnavigated the world.
The Alpha AXP, part 17: Reconstructing a call stack
Putting the information into practice.
The Alpha AXP, part 16: What are the dire consequences of having 32-bit values in non-canonical form?
It depends on what the next calculation is.
The Alpha AXP, part 15: Variadic functions
Keeping two sets of books that eventually become one.
The Alpha AXP, part 14: On the strange behavior of writes to the zero register
Room for future optimization.
Yes, that was a horrifically awkward video, but it wasn’t the Windows 95 launch
Some sort of sales event, probably.
The Alpha AXP, part 13: On treating a 64-bit processor as if it were a 32-bit processor
It's all in the point of view.
The Alpha AXP: Part 12: How you detect carry on a processor with no carry?
The same way you do it in C, which also doesn't have a carry.
The Alpha AXP, part 11: Processor faults
Sometimes you know where it happened. Sometimes you don't.
The Alpha AXP, part 10: Atomic updates to byte and word memory units
Putting together some things we've learned.
The Alpha AXP, part 9: The memory model and atomic memory operations
When does it happen? I have no idea!
The Alpha AXP, part 8: Memory access, storing bytes and words and unaligned data
Those little pieces.
The Alpha AXP, part 7: Memory access, loading unaligned data
Now it gets harder.
The Alpha AXP, part 6: Memory access, basics
Start with the easy cases.
The Alpha AXP, part 5: Conditional operations and control flow
But there is no flags register.
The Alpha AXP, part 4: Bit 15. Ugh. Bit 15.
Let's make some bits.
The Alpha AXP, part 3: Integer constants
Building them up a piece at a time.
The Alpha AXP, part 2: Integer calculations
It's all fun and games until somebody does sign extension.
The Alpha AXP, part 1: Initial plunge
Pretty registers, all in a row.
Wrapping some other scripting language inside a batch file
Polyglot to the rescue.
Decomposing file paths (and extracting other information like file size, date and time, and attributes) from a batch file
FOR to the rescue.
Why does attempting to echo an undefined environment variable result in the message “ECHO is on”?
Because that's what happens when you echo nothing.
The redirection can come anywhere on the line, and you can use that to get rid of the spaces
Up front and personal.
The redirection can come anywhere on the line, so watch out for those spaces
The operator vanishes.
Can I throw a C++ exception from a structured exception?
Technically okay, but it's unusual and doesn't solve your problem.
How am I supposed to free the memory the system allocates in the SetPrivateObjectSecurity function?
It comes from the process heap.
Trip report: Sequim Lavender Festival and the Olympic Game Farm
Some learned travel tips.
Wrapping up 2017’s extended CLR Week-and-a-half with some links to other CLR trivia
Additional useless reading.
If there is no difference between two options, choose the one that is easier to debug
Because you're going to be debugging it eventually.
How can I find out how many threads are active in the CLR thread pool?
Let's answer the question, but then look at the scenario.
The perils of async void
Go on without me.
Crash course in async and await
Hang on a second, I'll get back to you.
Do people write insane code with multiple overlapping side effects with a straight face?
I guess some do.
Why does the assignment operator in C# evaluate left to right instead of right to left?
Because that's what people expect, for certain values of "people".
Revisions to previous discussion of the implementation of anonymous methods in C#
All instance all the time.
Discussion of how to add UTF-16 support to a library that internally uses UTF-8
Convert it, but make sure it can convert back.
Customizing the window handle for item enumeration in IShellItem
It's on the site.
Why is the maximum number of TLS slots 1088? What a strange number.
It's a little less strange in binary.
Microspeak: To stand up
To get something working and available for use.
On the circular path from RAII to crazy-town back to RAII: Thoughts on emulating C#’s using in C++
A trip around the block.
How can I tell whether two paths reside on the same underlying volume, so I can know whether they can be hard-linked?
Don't try to guess. Just do it.
Debugging tip: Use .frame /r to recover nonvolatile registers from the stack frame
Saving you the trouble of reconstructing it manually.
How fair are SRW locks, particularly when there are both readers and writers?
Not fair! As with the other Windows synchronization objects.
Urban and suburban camouflage
Hey, what's that in my backyard?
Emulating the C# using keyword in C++
The co_await enables new patterns.
2017 mid-year link clearance
Marking the halfway point.
Extracting pages from a PDF document and saving them as separate image files, C++/CX edition with co_await
Everybody seems to be converging on C#.
Extracting pages from a PDF document and saving them as separate image files, C++/CX edition with explicit tasks
Sliding over to C++/CX.
Extracting pages from a PDF document and saving them as separate image files, JavaScript edition with async
Diving into an upcoming feature of ES8.
Extracting pages from a PDF document and saving them as separate image files, JavaScript edition with Promises
Trying it out a different way.
Extracting pages from a PDF document and saving them as separate image files, C# edition
A Little Program I needed.
Trying to make the thread pool more responsive to a large queue of long-running work items
Convert them to tasks.
When can GetSecurityInfo API return ERROR_INSUFFICIENT_BUFFER?
It's the race condition called out in the documentation.
Summertime, and the lemonade is easy
Unearthing an old game from my youth.
Why is Explorer opted out of Data Execution Prevention and termination on heap corruption, and how effective is the policy to opt it back in?
It's out, but it quickly comes back in, unless you tell it to stay out.
How do I set the initial directory of the File Open dialog to a virtual directory?
Use the IFileDialog::SetDefaultFolder method.
Stuff my father-in-law says: On baking bread
Three hours.
Combining the work queue of distinct events, order not important, with an auto-reset event
Combining two solutions into a bigger solution.
Creating an automatic-reset event from WaitOnAddress
Completing the quartet.
Creating a manual-reset event from WaitOnAddress
A diversion, in the form of a different exercise.
Creating a semaphore with a maximum count from WaitOnAddress
The exercises continue.
Creating a semaphore from WaitOnAddress
More exercises.
The case of the longjmp from nowhere trying to open a registry key
Close your eyes and jump.
What will GetLastError() return after a failed InitOnceExecuteOnce?
Whatever you tell it to.
On enabling NX and ASLR for a module after the fact
You can flip the bit, but you can't regenerate relocation information.
Microspeak: ROB and Office Hours
Rhythm of business.
How can I register a program to auto-relaunch if it crashes or is terminated?
There is no system registration. You'll have to roll one yourself.
How likely is it that a window will receive a WM_NULL message out of the blue?
Not entirely unlikely, let's put it that way.
Comparing WaitOnAddress with futexes (futexi? futexen?)
Two different ways of creating a synchronization object out of nothing.
Extending our critical section based on WaitOnAddress to support timeouts
Ooh, look, a new feature.
Why isn’t the original window order always preserved when you undo an Aero Shake?
Acts the same way as undoing a Minimize All, since that's basically what it is.
Does DebugBreak work to launch the debugger, or doesn’t it?
It does, eventually, but not because it is DebugBreak.
Why are hidden files with a leading tilde treated as super-hidden?
Because in practice they are ultra-temporary.
Diagnosing why you cannot create a stable subkey under a volatile parent key
You can't do it, but why is the parent volatile?
Some questions about unflushed data and calling FlushFileBuffers on a new handle to a file
Will it get flushed out eventually?
What do these hard drive icons mean?
Various kinds of BitLocker, mostly.
Why doesn’t searching my Start menu with Cortana find Internet shortcuts in my All Programs list?
Because our A/B testing showed that showing them was worse.
Debugging a GDI resource leak: Case study
If it leaked once, it'll leak again.
Why is the !locks command called !locks even though it debugs only critical sections?
Because those were the only kind of locks, back in the day.
Why do my PDF file associations get reset every time I restart?
Hey, that doesn't look right.
There’s a group policy for Action Center, and another one for Action Center
Two things with the same name, how confusing.
At least it wasn’t on a Web page with the warning “Beware of the leopard”
But it was simple.
A question about avoiding page faults the first time newly-allocated memory is accessed
What are you trying to optimize?
How to calculate the resulting security descriptor of a child object without creating it
Pretend that it's a private object.
Revised notes on the reliability of FlushFileBuffers
A check-in on what's happened over the past few years.
The early Windows phone devices were liquid-cooled, sort of
Soda is a liquid, right?
Couldn’t we fix the lackey catastrophe by using #pragma init_seg(user)?
That doesn't help, for more than one reason.
Remember that in a stack trace, the addresses are return addresses, not call addresses
It's where the function is going to return to, not where it came from.
The interaction between AppBars and Windows 10 virtual desktops
They apply to all virtual desktops.
Why don’t I get thumbnails for files that are marked offline?
Because offline files are assumed to be expensive to access.
Microspeak: Work-back
Start and the end and work backwards.
Those blue boxes all over the place, I always wondered what they were for
Non-electronic mail.
Why doesn’t SHGetFileInfo give me customized folder icons?
Because you asked for it that way.
Why does the compiler generate memory operations on the full variable even though only one byte is involved?
Store-to-load forwarding.
Static hooking through predefinition
Creating your own hook points.
Why are there two incompatible ways of specifying a serial port baud rate?
Toto, I don't think we're on an IBM PC XT any more.
How do I kill a program that hung with an always-on-top fullscreen window?
Hey, look at that desktop over there.
Filtering the Browse for Folder dialog so it shows only drive letters
An exercise in filtering.
Application crash reported as security vulnerability, but you never crossed the airtight hatchway
A crash is not a priori a security vulnerability.
On generating sentinel pointer values in Windows
That's not a pointer. <B>This</B> is a pointer.
Under what conditions could a commit of reserved memory fail?
Usually because you are out of memory, but really it's when you're out of commit.
That time a customer reported an error in the map used by Flight Simulator
But whose map is right?
Why does my __FILE__ macro produce an invalid address, which mysteriously becomes valid a few moments later?
It's not there until somebody demands it.
How can I atomically leave a critical section and delete it?
Even if you could, it wouldn't help you.
Can memcpy go into an infinite loop? Why is it being blamed for a busy hang?
Look at the bigger picture.
How do I get the current directory for a non-current drive?
GetFullPathName will tell you.
The Windows 8 close gestures, a retrospective
Top to bottom.
When I enable page heap, why is my one-byte buffer overrun not detected immediately?
I thought that was the point of page heap.
If I have a thread waiting on an event, and I call SetEvent immediately followed by ResetEvent, is the waiting thread guaranteed to be released?
Congratulations, you reinvented PulseEvent.
What can I do if I want to throw a C++ exception from my InitOnce callback?
There's the naïve solution and a sneakier one.
How do I programmatically obtain the user’s selected accent color in Windows 10?
It's in the UISettings object.
Microspeak: snap
To take a snapshot of the source code in order to produce a build.
How do I create a shortcut in the Send To menu that runs a program with a command line option?
Put the option in the shortcut target.
A survey of the various ways of creating GDI bitmaps with predefined data
So many to choose from.
For sale: One TARDIS, working (lights), you must pick up from Vancouver
Time travel circuits disabled by Time Lords, however.
The gradual erosion of the SEM_NOOPENFILEERRORBOX error mode
It does less and less, until it basically does nothing.
A brief discussion on how best to respond to the end-session messages
You can start early, but be aware that the user might change their mind.
Explorer is a single-instance application, but you can find other ways to get the effect of running a separate instance
Look for the explorer browser helpers.
How real-mode Windows loaded code from the disk, and how you could use that to minimize disk swapping
Send in the clones.
When you submit a security vulnerability report, we go the extra mile and try to fix your typos
Even if the typo is what confused you.
Responses to various ideas on how to get people to stop using that leaked build
Over-engineering the solution.
You can peek to see whether your delay-loaded function loaded successfully
Predicting the future.
Why does the volume control let me set the volume only to even numbers?
Because pressing Volume-Up 100 times would be really annoying.
Secret passages on Microsoft main campus, episode 2
Getting from one point to another.
Happy St. Patrick’s Day. Watch out for that throne.
A challenger from North Bend.
Not interested in college basketball? No problem. Follow the Name of the Year 2017 bracket
The greatest names of real people.
If I want to maintain a free list of pages, should I use MEM_RESET or MEM_DECOMMIT?
It depends.
How do I provide data to the sharing pane from a Win32 desktop application?
Continuing the interop pattern.
How do I show the sharing pane from a Win32 desktop application?
Unwrapping the projection, but now with interop.
Why is Alt+D the keyboard shortcut for putting focus on the address bar?
Because it was Ad&dress.
Raymond’s highly scientific predictions for the 2017 NCAA men’s basketball tournament
This one will definitely work, right?
Which languages are fully-localized by Windows?
And your little console too.
Is GENERIC_ALL equivalent to GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE?
Only if the object says so.
How do I keep thread pool threads, or other threads in general, from competing with my render thread for CPU?
You assign them to the default CPU set.
How do we improve the performance of conhost processes when we ping a bunch of servers?
How about avoiding them entirely?
Microspeak: to reason over
To make programmatic decisions based on, usually to produce a higher-level result.
Some internal developer chatter on a bug that caused your screen to turn black
A little dry humor for your amusement.
The case of the 32-bit program that tries to load a 64-bit DLL
A continuing saga which ultimately comes to a resolution.
What happens when you tell a Millennial to take pictures of a party
Oh, how tasty.
Don’t forget to implement canonical names for verbs in your shell context menu extension
The system uses it to find you later.
Want to include a gift message with your tires? Nice try.
You'll have to show your love some other way.
Why does my attempt to acquire an SRW lock block even though !locks report no locks held?
!locks is looking for critical sections.
Great moments in journalism: “Confirmed Microsoft Surface Pro 5 launch date”
Confirmed by rumor?
Baking soda has hundreds of uses, but what about what it says on the tin?
Can you bake with it?
How do I disable the press-and-hold gesture for my window?
Digging back into ancient history.
Eventually you reach a critical mass of LEGO pieces where you can build most things from what you already have
Just look it up.
The system manages the system image lists; don’t go changing the art on the walls
You can read from them, but don't modify them.
How am I supposed to print my print-at-home tickets if I can’t reproduce them?
Legal disclaimers from the past.
How to create a folder that inherits its parent’s ACL, and then overrides part of it
Creating it with a custom security descriptor isn't working.
Those Year 2000 disaster preparedness trucks were originally there for a different reason
Originally for long-haul testing in the power-unstable Pacific Northwest.
What little kids think of lifeguards
Lots of yelling.
Psychic debugging: Why does opening a command prompt always print a weird error message?
Check your AutoRun.
The 2017/2018 Seattle Symphony subscription season at a glance
The pocket reference guide for 2017/2018.
Another more efficient solution to the problem of a long-running task running on the thread pool persistent thread
The thread-agnostic change notification.
Follow-up: The bus that straddles traffic
Sitting motionless over half a road.
A more efficient solution to the problem of a long-running task running on the thread pool persistent thread
Break it up a little more.
How do I fix the problem of a long-running task running on the thread pool persistent thread?
Hey, you, get off of my thread.
Man, this housing downturn is hitting everyone, follow-up
Down we go.
Why did my thread pool stop processing work once it hit a long-running work item?
Because you ran the work item on the persistent thread.
Pipelining your laundry, and the ensuing silliness
When geeks go overboard.
Advertisement for ink cartridges doesn’t do all the math
Maybe they are trying to minimize the frequency of ink cartridge changes.
Sometimes you get so worked up about the compatibility consequences of a change that you miss the obvious
It clearly was not happening before, because it crashed.
How do I do an interlocked exchange of a hat pointer?
Perform a raw exchange of the underlying native pointer.
Suspicious memory leak in std::basic_string
There are not the PODs you are looking for.
Why are all Windows drivers dated June 21, 2006? Don’t you ever update drivers?
Are you just a bunch of slackers?
Microspeak: Placemat review
Put the fork here and the knife there.
My proposal for an episode of the new Star Trek series
Darmok says, "Internet, its tubes clogged."
Why does a Microsoft mouse accept two batteries even though it works just fine on only one battery?
To reduce the frequency of battery changes.
It is a great deal and not a great deal, both at the same time
At least until you open the box.
Why am I getting a crash at shutdown inside the thread pool?
Stop talking to a dead thread pool.
Some friendly advice from the Redmond Public Safety department on nighttime nude jogging
Stay healthy out there, folks.
Are DDE and WM_COPYDATA related as IPC mechanisms?
Specifically, is one dependent on the other?
I wasn’t fooled into thinking the Star Wars trench run was along the equatorial trench, but I was fooled anyway
I thought it was a different route entirely.
How am I supposed to free the information passed to the SetSecurityInfo function?
You allocated it. You get to free it.
Why does my Surface power brick keep blinking on and off?
Power negotiations break down.
Creating an object on the other side of the airtight hatchway isn’t yet a security vulnerability
What can you do with that object?
How can a COM local server keep itself alive even though there are no active clients?
CoAddRefServerProcess to the rescue.
How can I control the directory from which my delay-loaded DLL is loaded?
Use the hook.
Are there alternatives to _lock and _unlock in Visual Studio 2015?
This is unlikely to work.
Why do my program’s notifications sometimes show a small icon, and sometimes a large icon?
And why does it sometimes show the program name?
How do I prevent users from terminating a service?
Use the ACL.
How important is it nowadays to ensure that all my DLLs have non-conflicting base addresses?
Not so much, since ASLR changes it anyway.
A fine detail on how DLLs are relocated as the result of a base address collision, and consequences
Fixed up as necessary, but only as necessary.
Does ASLR relocate all DLLs by the same offset?
No.
Microspeak: ladder up
Let's puzzle it out.
How come my CreateMutex call sometimes fails with Access denied?
Because the creator didn't grant you access.
A survey of the various ways of declaring pages of memory to be uninteresting
Let me tell you how much I don't care.
How do I detect Windows 10 if I cannot GetProcAddress for the function IsWindows10OrGreater?
Just like in a cheesy movie, the answer was inside you all along.
Applying a permutation to a vector, part 6
Completing an earlier exercise: The reverse permutation.
Applying a permutation to a vector, part 5
Error checking.
Applying a permutation to a vector, part 4: What is the computational complexity of the apply_permutation function?
It's linear, though it doesn't look that way at first glance.
Sorting by indices, part 2: The Schwartzian transform
Decorate-sort-undecorate.
Sorting by indices, part 1
Putting things together.
Applying a permutation to a vector, part 3
Permuting more than just vectors.
Applying a permutation to a vector, part 2
To swap or not to swap. That is the question.
Applying a permutation to a vector, part 1
Tinkering with an algorithm.
2016 year-end link clearance
Another year.
The invisible work of preparing PC BIOSes for the year 2000
Nursing the BIOS into the new century.
The evolution of the text size limits related to the standard static control
Smaller, then bigger.
The case of the four unlabeled toggle buttons
Make up whatever you like.
Why don’t I get properly translated program output after installing the corresponding language pack?
There's localization and there's localization.
Wireless AC is, unfortunately, not what it sounds like
The strange naming conventions of IEEE 802.11 standards.
The mother lode of well-known SIDs
Jackpot.
Another pattern for using the InitOnce functions
The synchronous two-phase initialization.
What is the maximum numeric value for a socket, and what is the maximum number of sockets a Windows program can create?
You can create as many as you want, subject to the usual resource constraints.
If you ask robocopy to destroy the destination, then it will destroy the destination
Be careful what you ask for. You might get it.
Why can’t VarDateFromStr parse back a Hungarian date that was generated by VarBstrFromDate?
Parsing is hard. Date parsing doubly so.
My colleague who thought he held the unofficial record for consecutive months of skiing
He stumbled upon an entire community of like-minded skiers.
How bad is it to delay closing a thread handle for a long time after the thread has exited?
Not too bad, as long as you don't make a habit of it.
Dubious security vulnerability: Discovering the salt
The salt is not a secret.
Can a server-side Web application trigger the creation of thumbs.db files?
Probably not.
Why does tapping the Alt key cause my owner-draw static control to repaint?
Time to draw the underlines.
Answers to a customer’s questions about memory and DLLs
Simple questions and hopefully simple answers.
What is this race condition that the OpenMutex documentation is trying to warn me about?
Open it, but it won't come.
Why don’t I get a broken pipe when the child process terminates?
The pipe isn't broken yet.
How can I reset a PC if I forgot the administrator password?
What I reboot three times is true.
The case of the unexpected ERROR_ACCESS_DENIED when calling MapViewOfFile
Mind those weakly-typed integers.
Why do I get a _BLOCK_TYPE_IS_VALID debug assertion failure when I try to delete a WIC pixel buffer?
Because that's not your pixel buffer.
What is __wchar_t (with the leading double underscores) and why am I getting errors about it?
It's the internal wchar_t.
What could be happening in Safe Mode to make my heap corruption bug go away?
It's more about what's not happening.
The case of the volume label that doesn’t change
Who can read it?
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?
If you need nothing, then ask for nothing.
The Gävle Goat is now 50 years old
Welcome to Gävle. Please don't burn down our goat.
Lock free many-producer/single-consumer patterns: A work queue of distinct events, FIFO
No cutting in line.
Turkeys Away: An Oral History
The most famous sitcom Thanksgiving Day episode.
Lock free many-producer/single-consumer patterns: A work queue of distinct events, order not important
Each one is different in its own special way, but we don't care what order they are processed.
Lock free many-producer/single-consumer patterns: A work queue of identical non-coalescable events
They're all the same, but each one counts.
Lock free many-producer/single-consumer patterns: A work queue where the last one wins
There can be more than one, but only the last one counts.
Lock free many-producer/single-consumer patterns: A work queue with task coalescing
Starting out simple.
Why does calling SetForegroundWindow immediately followed by GetForegroundWindow not return the same window back?
Because it's not the foreground window... yet.
Is RunAsInvoker a secret, even higher UAC setting?
Actually, it's a secret even lower UAC setting.
When you decide to travel at the speed of light, you have to accept the consequences
Lots of things break down.
The speed of light is unlikely to improve: consequences
The limits of resolution.
What does the shield over a WiFi network mean?
It means that the network is not secure.
The long-awaited Redmond Costco opens today, and some useless Costco trivia
Home sweet home.
If you don’t blow up a debug session every so often, you’re not debugging hard enough
Life on the edge.
Under what circumstances will GetProcessTimes report that a process exited before it was created?
If it hasn't exited yet.
Zeroing out my memory does cause them to page in faster after all
Thanks to a special check in the memory manager.
Why do my file creation, access, or modified time disappear if I set it to midnight on January 1, 1980?
Mind the epoch.
How do I programmatically add a folder to my Documents library?
You can use SHAddFolderPathToLibrary, but there's a catch.
Why is my crash dump file filled with 0xAAAAAAAA?
No, it's just that the original data was scrubbed out.
Solving the problem instead of answering the question: How do I get this RichEdit control to look just like a static control?
That's not your problem.
What happens if you call RevertToSelf when not impersonating?
Nothing, but be careful.
Windows file system compression had to be dumbed down
Adjusting the trade-off.
This processor has no stack (insert spooky laughter)
Nothing to push here.
Why does SetThreadPriority sometimes take a really long time?
Because you asked for it.
How to electrify your own fence: ProcessStrictHandleCheckPolicy
Don't touch that; it's a live wire.
Why does the documentation for ReadFile say that the lpNumberOfBytesRead parameter is optional when it is sometimes mandatory?
In the fine print, due to incomplete expressiveness.
Microspeak: lift up
Take a look around you.
Why is Identical COMDAT Folding called Identical COMDAT Folding?
Common data, as in FORTRAN.
Is there anything better than GetThreadTimes for obtaining per-thread CPU usage information?
QueryThreadCycleTime.
Using DuplicateHandle to help manage the ownership of kernel handles
That one's mine.
Three short questions about LogonUser (with answers!)
The answers are probably the most useful part.
Was it intentional that the Media Control Interface has the same acronym as a telecommunications company?
Why yes, actually.
The Windows 8.1 ship-it awards were yellow
Code name Blue.
How can I force memory to be allocated above the 4GB boundary (for debugging purposes) on Windows 7?
Sadly, no easy solution.
Dubious security vulnerability: Attacking the application directory in order to fool yourself?
Look over there. Ha ha made you look.
Nasty gotcha: The inadvertently named resource
No such thing as undefined.
Oh, you’re with them?
Unconscious biases in the workplace.
A Little Program to fix one particular type of mojibake
Keep your eye on the code page.
How can I get the default code page for a locale?
Ask GetLocaleInfo.
How do I cancel autoplay from a wizard page?
You need to listen on the top-level window.
Why doesn’t my custom-drawn trackbar get a paint notification when the position changes from 1 to 0?
It had no visible effect.
Wow, that’s amazing. You got Picabo Street and Alberto Tomba to autograph the same poster!
Partly true.
You can register your child’s name in any language providing you use any Unicode character
Happy birthday, Unicode!
When are global objects constructed and destructed by Visual C++?, redux
Adding another column to the table.
The lackey catastrophe
You know it will be done, but you don't know when.
When can you free the memory backing the HSTRING you created with WindowsCreateStringReference?
Nothing you haven't had to deal with already.
What’s up with Windows developer tools being written in perl?
It's socially acceptable.
It says that I should use USB usage page 1 and usage 6 to get raw keyboard data, but what if I have a PS/2 keyboard?
The numbers came from the USB HID specification, but that doesn't require the keyboard to be USB.
When you break into a user-mode application in the kernel debugger, how do you connect a user-mode debugger?
Make the program its own bridge.
Dither me this
Where did the error go?
The case of the system() call that returned before finishing
Study the output more carefully.
The social skills of a thermonuclear device: Ruining a conversation
The party's over.
It’s an unfortunate choice of data type for the file system redirection cookie
The untyped pointer strikes again.
Does the page table entry really have a sad-face for pages that are reserved?
Not exactly, but it's not as silly a question as it sounds.
Decoding the parameters of a thrown C++ exception (0xE06D7363), revisited
The mysterious second parameter.
What exactly does the msWindowLength parameter to SetThreadpoolTimer mean?
It's the maximum delay, but never the maximum anticipation.
What are these ghost drivers named dump_diskdump.sys and other dump_*.sys that didn’t come from any file?
Send in the clones.
How can I have a window that rejects activation but still receives pointer input?
The obscure return values of the WM_MOUSEACTIVATE message.
How can I get the memory manager to prefetch bigger chunks of data from my memory-mapped file?
Explicit prefetch.
How can I change a registry key from within the debugger?
There's the hard way and the easy way.
If I zero out my memory pages, does that make them page in faster?
Not really.
How to get people who installed a leaked build to stop using that build?
Change the wallpaper.
The complicated engineering behind an ice cream social
Lost in translation.
A customer question about shortcuts that don’t have a target path
Digging into the question to find the solution.
Discardability in drivers has nothing to do with discardability in user-mode (which has nothing to do with discardability, really)
Overloaded flags.
The ship date predictor: Redux
Each project is different.
What is the NTDiskQuotaSidCache.ndx file for?
It's the SID cache for the disk quota control panel.
Detecting what language or script a run of text is written in, redux
One step closer to actually doing it.
Spurious wakes, race conditions, and bogus FIFO claims: A peek behind the curtain of WaitOnAddress
Watch the gears turn.
Soarin’ over California + Seattle = Wings over Washington
I wonder what it's like.
Implementing a critical section in terms of WaitOnAddress
Building things out of other things.
The International Fair Play Committee announces the Rio 2016 Fair Play Awards, but spends most of the time congratulating themselves
Sporteaucratic nonsense.
Implementing a synchronization barrier in terms of WaitOnAddress
Kicking the tires by building another kind of tire.
WaitOnAddress lets you create a synchronization object out of any data variable, even a byte
Pick a byte, any byte.
Adventures in application compatibility: The bogus memory calculation
Let's add some numbers together, shall we?
Is it okay to call TryAcquireSRWLock from a thread that has already acquired the lock?
No.
If I have a modeless dialog box with custom accelerators, which should I call first: IsDialogMessage or TranslateAccelerator
Only one way works.
On installing a custom unhandled exception filter and intentionally raising an exception to get its attention
Mind those stack frames.
There are really only two effectively distinct settings for the UAC slider
Off and on.
Things I learned from my recent trip to Vancouver
It's not butter.
How can I debug a function that has been subjected to COMDAT folding?
The easy way is to mutate the function.
On the importance of making sure WaitForInputIdle doesn’t think you’re idle, episode 2
WaitForInputIdle is how the shell knows that your DDE server.
I’m speaking at the brand new Microsoft Canada Excellence Centre tomorrow
But only for Microsoft employees, sorry.
On the importance of making sure WaitForInputIdle doesn’t think you’re idle, episode 1
WaitForInputIdle is how the shell knows that your DDE server.
How to create a file mapping that allows others to open the file in exclusive mode?
This is a job for opportunistic locks.
What is a ZDP, and what’s so Z about it?
Zero Day Package, but not that kind of zero day.
Why didn’t Windows 95 suck the brains out of the XMS driver?
It was working fine up until now.
The case of the hung Explorer window
Decoding the deadlock.
The origin story of the Microsoft ninjacat
So it begins.
Using #pragma detect_mismatch to help catch ODR violations
There can be more than one, but they must be the same.
Why don’t I get a file deletion confirmation warning from Explorer when I undo a copy?
Because this is not really a deletion operation.
How do I disable edge gestures when my window is full screen?
System.EdgeGesture.DisableTouchWhenFullscreen.
Further discussion of the synchronization barrier
It's really just a switch.
How can I check whether a parameter is a pointer to a stack variable?
Check it against the thread limits.
Why does setting the horizontal scroll bar range for the first time also set the vertical range, and vice versa?
An attempt at delay-initialization.
Why does sharing a folder in Explorer grant full permission on the share to everyone?
The ACLs will do the work.
Is there a Windows API for IntelliSense?
That's not really an operating system thing.
What is the significance of changing the registration for CLSIDs to point to a private copy of MSXML3?
You hijacked the CLSID, which is not going to end well.
If you don’t want the changes to be permanent, the don’t pass the flag that says that you want the changes to be permanent
Stands to reason.
Microspeak: Tick-tock
Who's doing what when?
Having trouble with Windows Hello face recognition? Try a Jedi mind trick!
This is the user you are looking for.
When I tell Windows to compress a file, the compression is far worse than I get if I ask WinZip to compress the file; why is that?
The different compressors have different goals.
Trying to recover from enhancement software that generates fake input incorrectly
Try to reprocess it the right way.
How can I preallocate disk space for a file without it being reported as readable?
Set the file allocation information.
What happens if I have multiple asynchronous ReadDirectoryChangesW calls outstanding on the same directory handle?
It doesn't matter because you already lost to the scheduler.
Why does the Windows 8 sign-in animation slide upward?
Opening like a curtain.
Where can I get the glossary of Microsoft’s standard translations for computer terms?
At the Microsoft Language Portal.
It rather involved being on the other side of this airtight hatchway: Elevating the elevator
You already control the horizontal and the vertical.
Even if you modify a high contrast theme so it isn’t quite so high-contrast, it’s still a high contrast theme
The bit is still set.
Mathematical term or Hollywood movie?
Another quiz.
How can I detect whether my PC is in tablet mode?
You ask for the user interaction mode.
Observing the bizarre rumor mill from the other side
Make it up, and then ask if it's true.
Attention all humorless technaheads
But still no love for Clippy.
How exactly are page tables allocated on demand for large reserved regions?
Just create a placeholder page directory entry that says "Nothing to see here."
2016 mid-year link clearance
Out you go.
How can I detect whether the Game Bar is covering my window?
A little interop.
Why does the Windows calculator generate tiny errors when calculating the square root of a perfect square?
Because it doesn't know that it's a perfect square.
If I have multiple attached keyboards, how can I read input from each one individually?
Raw input will tell you.
Why is my message queue full of WM_TIMER messages?
Where do timer messages come from, anyway?
Why does the x64 calling convention reserve four home spaces for parameters even for functions that take fewer than four parameters?
Variadic functions.
Using the Windows::Globalization::Calendar object from a Win32 app
An introduction to projection.
How to recognize DNS zone scavenging availability timestamps from quite a long way away
A rather peculiar format.
Peeking inside an IShellItem to see what it’s made of
There are a folder and a pidl in there, but only if you look.
How can I update my WinForms app to behave better at high DPI, or at normal DPI on very large screens?
Understanding DPI awareness.
Why do I get a spurious WM_MOUSEMOVE message whenever Resource Manager is running?
An artifact of certain window manager operations.
Raymond’s complete guide to HSTRING semantics
It's reference-counted, except when it isn't.
Is there a way to change the minimum size for large pages?
It's set by the processor, not Windows.
What’s so special about the number 64 when it comes to TLS slots?
That's how many there were, a long time ago.
Investigating an app compat problem: Part 3: Paydirt
Finding the answer.
Investigating an app compat problem: Part 2: Digging in
Understanding the scenario a little more.
Investigating an app compat problem: Part 1: The initial plunge
Seeing the proximate cause.
I finally finished this awesome game called Photoshop, let me send you a video
Taking the Game DVR to the next level.
If I create multiple selectors each of size 4GB, do I get a combined address space larger than 4GB?
Not really
Why does SetFileValidData fail even though I enabled the SE_MANAGE_VOLUME_NAME privilege?
It's all in the timing.
How can I tell whether a file is on a removable drive, a fixed drive, or a remote drive?
Beware of the volume mount point.
Why does SHGetKnownFolderPath fail when impersonating?
Because there's a special way to call it for impersonation.
The chain reaction started when a customer’s line of business application doesn’t work with UNCs
Fighting over a registry key.
Printing the name and position of the focused item on the desktop
You already know how to get the view, so ask the view.
Diagnosing a crash in unloaded_something.dll
Find out what used to be loaded there.
Debugging session: Which of the many things happening in this single line of code is the one that crashed?
Let's go to the disassembly.
How can I generate a stack backtrace that is independent of ASLR?
Use module offsets rather than absolute addresses.
How do I create a directory where people can create subdirectories but cannot mess with those created by other users?
Advanced ACL games.
Security through lying
Factual errors make it harder for the good guys.
How long do I have to keep the SECURITY_ATTRIBUTES and SECURITY_DESCRIPTOR structures valid after using them to create a file?
Once CreateFile returns, they aren't needed any more.
Why did the friendly name for the Network Service account change?
Nobody promised it wouldn't.
Why doesn’t RevertToSelf undo the most recent SetThreadToken?
It removes all impersonation; it doesn't restore it.
But Australian Telecom loves it!
Weighted average.
Wow, that article sounds an awful lot like something I would have writt… hey, wait a second
Deja vu.
Is Metro on fire today?
Single-serving.
Why am I being told that my message ID is too large?
Look at the message format.
How come a duplicated token doesn’t behave identically to the original?
The inside's the same, but the outside is different.
What’s the difference between duplicating the handle to a token and duplicating a token?
Are you sharing an object or are you creating two objects?
How can my CPU be running faster than the maximum speed?
Remember the Turbo button?
Taking shortcuts when following driving instructions doesn’t always pay off
Back to the source.
Is it okay to acquire an SRWLOCK recursively? (And why not?)
The documentation says it's not allowed, so it's not allowed.
How can I write an unkillable program, redux
License to not be killed.
How can I detect whether the user’s keyboard has a Break key?
Looking at the problem the wrong way.
Getting MS-DOS games to run on Windows 95: Not enough XMS handles
Of course I got it, right?
Does Mulan speak Chinese?
Not really.
Startup apps start up when I tell them
It's not really a useful performance metric.
What does QueryThreadCycleTime actually count?
Whatever the CPU wants.
Is there an API for redrawing a specific window from another application?
Once again, turns out to be the wrong question.
How does Explorer calculate “Size on disk”?
Very simplistic.
Why can’t I pin a document to the taskbar?
Because that's not what the taskbar is.
Getting MS-DOS games to run on Windows 95: Too much EMM memory
Now that you got it, you need to find a place to put it.
Should I be concerned that WaitForSingleObject is taking a large percentage of my performance test’s execution time
What you've got there, my friend, is a WaitForSingleObject stress test.
It rather involved being on the other side of this airtight hatchway: Invalid parameters from one security level crashing code at the same security level (doesn’t get old)
You never crossed a security boundary.
Why are mouse wheel messages delivered to the focus window instead of the window under the mouse?
Keyboard modifiers.
Why is there a screen that says “It is now safe to turn off your computer”?
Because that's when you know.
Getting MS-DOS games to run on Windows 95: Too much memory!
Another case of intentionally under-reporting memory.
What happens if I call EnumPropsEx while another thread is mutating the properties?
You get a best-effort.
Even though the target audience may be programmers, it can still be seen by users
Freaking out over programmer jargon.
If relocated DLLs cannot share pages, then doesn’t ASLR cause all pages to be non-shared?
ASLR is careful to keep sharing alive.
Inherited access control entries are captured when the child object is created
Frozen in time.
Getting MS-DOS games to run on Windows 95: The interrupt flag
Incomplete virtualization strikes again.
Why does FindExecutable behave erratically for files with extensions longer than three characters? (And what can you do about it?)
Short file names strike again.
Why can’t the debugger call GetFinalPathNameByHandle via .call?
Because it doesn't know how.
How does GetFinalPathNameByHandle choose the name if there are multiple names due to hard links?
It picks the one you you used to open the file.
Dubious security vulnerability: Disk space consumption
You have permission to use all the disk space you can.
Getting MS-DOS games to run on Windows 95: Working around the iretd problem
Speed Racer in the Challenge of Racer X, please make it stop.
Is it really a prank if the victim doesn’t realize there’s a prank going on?
Oblivious.
Why are there four functions for parsing strings into GUIDs, and why are they in three different DLLs?
Different historical contexts..
The numerology of the build, redux
But why 16?
Why doesn’t a program show up on the Start menu’s Recently Used Programs list if I just used it to open a document?
You have to actually use the program directly, at least once.
Getting MS-DOS games to run on Windows 95: Virtual memory
Memory access is uniform and free, right?
Fixing a floating point exception when operating on NaN
Generate it at compile time.
Why does PathIsUNC say that paths that begin with \\?\ are not UNCs?
Because they aren't.
Don’t be helpless: You can find information too, if you try (episode 3)
Look around you.
How can I find out how much disk space the WinSxS folder is really occupying?
Untangling the links.
Were there specific criteria for making a game work at all costs vs. leaving it be if it had problems too weird to debug?
It was basically up to me.
What are the consequences of reserving a huge amount of memory, most of which is never committed?
It's mostly harmless now.
Why not use weak linking to solve the retargetable library problem?
A discussion.
Randomly-generated passwords still have to be legal strings
Well-formed strings according to the encoding.
Why doesn’t this registry hack for disabling autorun work?
Because it never claimed to.
Adventures in UI Automation: Scraping the Driver Files dialog
Drivery goodness.
On week numbering in the United States
We don't really do it.
Could there be any problems with calling GetModuleFileNameEx on your own process?
Yes.
String comparisons against program output is not usually the best solution
Look for programmatic interfaces.
If what you’re doing is undocumented, it’s not guaranteed to keep working, and your promise not to complain doesn’t really hold water
Because that's what undocumented implies.
On word breaking in Chinese and Japanese
Different rules.
Why not auto convert week-based time zone information to date-based?
What an adorable snowflake.
Are SetProp and RemoveProp thread-safe?
As thread-safe as they can be.
How can I get the name of the function that crashed given just a module name and offset?
Resolving symbols offline.
You kids are so cute, thinking you invented email
It predated the Internet, you know.
The 2016/2017 Seattle Symphony subscription season at a glance
The pocket reference guide for 2016/2017.
How can I get the original shortcut target path with environment variables unexpanded?
You'll have to dig into the data list.
Changing a loop into a promise or task chain
Crack open your textbooks.
How do I preload a chunk of memory into a memory-mapped file?
PrefetchVirtualMemory will do this.
A static_cast is not always just a pointer adjustment
That null pointer thingie.
Why does the date disappear from my taskbar, sometimes?
Because there's no room for it.
Finding the shortest binary string in a given interval
Narrowing in.
When I try to calculate a performance counter manually, the answer is off by a factor of 100
Because it's a percentage.
Nasty gotcha: VarCmp vs VariantCompare
Similar names, different return values.
Don’t just grab the foreground window and host UI on it, redux
Oops, it's not there any more.
I have difficulty following Swedish when spoken at conversational speed, and I count on being able to read the subtitles in order to catch up
This doesn't help.
If I select multiple files of different types, why does the Open verb disappear?
It won't always work.
How can I get the name for the user’s profile directory that is shown in Explorer?
You ask the shell namespace.
We batched up our COM requests and return a single stream of results, but the performance is still slow
Your stream marshaled by reference.
Debugging walkthrough: Diagnosing an NX exception
Leap of faith.
If somebody creates or deletes a file in a directory while I am enumerating its contents, what happens?
It's not really predictable.
Hey, you work for Microsoft. Do you know…?
Sometimes the longshot pays off.
How can I get the canonical name for a known folder?
You ask it.
The overly complicated rules for American football
Attempting to close a loophole creates another loophole.
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?
Of course not. That's why it's called "overlapped."
How do I prevent a child process from displaying the Windows Error Reporting dialog?
Take advantage of the fact that SetErrorMode is inherited.
Localization gotcha: The RTL question mark
Depends on the locale.
What happened to the ability to use … (three dots) to refer to the grandparent directory?
An old NetWare compatibility hack.
A brief tour of the console alias functions
Kicking the tires.
Does the thread pool have different handle access privileges? Why am I getting ERROR_INVALID_HANDLE?
The most common reason for getting ERROR_INVALID_HANDLE is that you have an invalid handle.
Why is getting the HP_HASHSIZE so weird?
Second-order logic.
Why does CryptDestroyHash crash, but only sometimes?
Improper destruction leads to undefined behavior, and undefined behavior includes "crashing only sometimes".
Some senior executives are afraid to provide feedback, because they know that their feedback will be given too much weight
Excess baggage.
How can I tell whether my console program was launched from Explorer or from a command prompt?
That's not actually what you want to know.
If I’m going to store a SID in a file, should I store the string form or the binary form?
Pros and cons.
What does the /V (verify) flag to XCOPY mean, and how did it get that way?
It doesn't mean much any more.
So how bad is it that I’m calling RegOpenKey instead of RegOpenKeyEx?
Mostly not bad, except for the gotcha.
What makes XCOPY so X?
It's extra awesome. But I don't know what the X stands for.
Some notes about the blog migration
Put your feedback here.
A puzzle involving dynamic programming, or maybe it doesn’t, episode 2
Once again, the hint is wrong.
What does this crash in TppRaiseHandleStatus mean?
Imagining how a feature was written.
When you start talking about numbers as small as 2⁻¹²², you have to start looking more closely at the things you thought were zero
Do the math.
My program for faking debugging demos
Looking behind the curtain.
Getting one’s paycheck from some mysterious pile of money
But at least you get to visit the receptionist.
Creating a shell extension that applies only to files with a very specific name
The AppliesTo tag.
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
The file on disk, the representation of the file, and the reference to the representation of the file.
It rather involved being on the other side of this airtight hatchway: Attacking the system clock
Tick.
Why does the mouse cursor jump a few pixels when you right-click on the Start button?
To make it easy to click the first item.
Why did Windows NT decline to support an undocumented flag to TrackPopupMenuEx?
Duh.
Slam City with Scottie Pippen (1995): A flashback
No video? No problem.
If you want to receive a message that is broadcast to top-level windows, you need a top-level window
Stands to reason.
2015 year-end link clearance
More random stuff.
Why is my call to ChangeTimerQueueTimer having no effect? (And another case of looking past the question to solve the problem.)
Because it's too late.
Why are Windows setup logs stored in a Panther directory? Does it have anything to do with the abandoned Panther project from the precursor to Windows 95?
Unrelated.
Determining how each Explorer window is sorted
Ask for the sort criteria.
When is the correct time to call FreeLibraryWhenCallbackReturns?
Any time during the execution of the callback is fine.
Why does my in-place tooltip dismiss itself as soon as it appears?
Because it's detecting itself.
Confusing gotcha: PSECURITY_DESCRIPTOR is not a pointer to a SECURITY_DESCRIPTOR
It's just an untyped pointer.
Unhandled Exception: Cannot print exception string because Exception.ToString() failed.
So that happened.
Allocating page file space without allocating RAM
Fixing an old tool.
Are views of memory-mapped files coherent within a single process? (And how this was the wrong question.)
Yes.
Dubious security vulnerability: Messing with the Recycle Bin
You're only screwing yourself.
You’d think that with the name TEMP, people wouldn’t expect it to be around for a long time
Temp stands for Temporary.
Great moments in forgetfulness: Does anybody have a copy of this file?
It's in a safe place.
Calculating integer factorials in constant time, taking advantage of overflow behavior
Too high! Too high!
Hasn’t the problem of updates being partially installed until the next reboot already been solved by changes in Windows?
Mostly, yes.
Why does OpenProcess return access denied, even if I enable debug privilege?
Asking for more than you need.
Why doesn’t findstr use the standard regular expression library?
What standard regular expression library?
How do I register a command on the desktop background context menu? (And how do I remove one I don’t like?)
Places to go, and places to look.
Enumerating all the programs that can launch a particular protocol
SHAssocEnumHandlersForProtocolByApplication
Why did disabling interrupts cause Windows 95 to hang?
Because compatibility.
A question about how to detect whether Windows Update needs the system to be restarted turns out to be the wrong question
For critical availability, don't install it until you are ready to reboot.
Hidden gotcha in the thread pool sample program on MSDN
That's a pretty small pool.
What does Ctrl+Enter mean? It depends on whom you ask
Maybe it enters a soft return, maybe it sends a command.
Enumerating all the programs that can open a particular file extension
SHAssocEnumHandlers.
In order to serve you better: Charging your credit card in your home currency
For a fee.
How can I append to a file and know where it got written, even if the file is being updated by multiple processes?
File locking strikes again.
The increasing urgency of a request to fill out a survey
Let's try that again.
Clarifying the documentation on wildcards accepted by FindFirstFile/FindFirstFileEx
Only in the file name portion.
We got around three
One in a million, or not quite.
Playing with synchroninzation barriers
All for one and one for all.
Investigating a problem constructing a security descriptor to deny thread-specific access rights to Everyone
Clearing up the confusion and deleting code.
Stupid JavaScript debugging tricks: Abusing the conditional breakpoint
Code injection.
If You Are The One: The crazy Chinese dating show
Serious inquiries only.
Why is the StartRunNOHOMEPATH policy so very specific about what it does?
Because that's what the customer asked for.
The ritual of choosing your next office
Cap and trade.
How can I get notified when the cursor changes?
Accessibility to the rescue, again.
Exploring the Supercute World of Hello Kitty
There's still time to get to the Hello Kitty Supercute Opening Party at the Experience Music Project, kicking off a four-month exhibition of Everything Hello Kitty. (Here are pictures from the Los Angeles leg of the tour.) Curiously, one of the events on the agenda for the opening night gala is a "Q&A with Hello Kitty" at 8:00pm, which is going to be interesting, seeing as Hello Kitty does not have a mouth. One of the exhibit's sponsors is UNIQLO, who I should remind you, has a very strange clock. Bonus chatter: EVA Air now has a thrice-weekly flight between Taipei and Houston, so you can now fly Hello Kit...
Diagnosing high CPU by studying profiling results, example
Why would a wait consume so much CPU time?
Why is January 1 being reported as the last week of the previous year?
Because the rules say so.
Oh, that’s probably why I’m in the Quake credits
I'm touching you!
It’s called “proofreading”, give it a shot why don’t you, episode 2
Collaterol.
I cloned a project, but the new project still groups with the old project on the taskbar
The Application User Model ID strikes again.
Some helper functions for interlocked pointer operations
Template-o-rama.
Why does the access violation error message put the operation in quotation marks, redux
It could be.
Sometimes a function returns NULL because NULL really is the answer
There is nothing there.
Changing the conditions under which ReadFile produces fewer bytes than requested
Where's the rest of me?
Microspeak: North star
Guiding principle.
How can I make my custom namespace extension get categorized correctly in My Computer?
Give it the appropriate description ID.
Why does the timestamp of a file increase by up to 2 seconds when I put it in a ZIP archive, then extract it?
The MS-DOS time format again.
When you open a securable object, make sure you pass the security mask you actually want (no more, no less)
You will get all you want, but you have to ask for it.
How do I create a wizard that contains none of the things that makes a wizard a wizard?
It's not a wizard, so don't use a wizard.
The Redmond Reality Distortion Field: Analogies involving high-performance cars, usually Ferraris
Vroom.
Are there any negative consequences to having a ton of files on the desktop?
Extra work.
CoGetInterfaceAndReleaseStream does not mix with smart pointers
Old school meets new school.
What are the rules for CoMarshalInterface and CoUnmarshalInterface?
Keeping an eye on the reference gets a little harder.
What are the rules for CoMarshalInterThreadInterfaceInStream and CoGetInterfaceAndReleaseStream?
Keeping an eye on the reference.
What is COM marshaling and how do I use it?
Keeping an eye on the reference.
How do I get the user-customized name of a mapped network drive?
Ask the shell. That is, after all, how the shell displays is.
I have the handle to a file; how can I get the file name from the debugger?
Build the call on the stack.
What’s the difference between UuidFromString, IIDFromString, CLSIDFromString, GUIDFromString…
Mostly the same if what you have is a stringized GUID; otherwise...
The MoveSecurityAttributes policy affects only how Explorer recalculates ACLs when a file is moved; everybody else is on their own
GUI policies tend not to apply to command line tools.
Why do Saturation and Luminance go all the way to 240, but Hue goes only to 239? And why 239 anyway?
Mapping a floating point number to a byte.
How do I get the user-customed name of My Computer or Recycle Bin?
Ask the shell. That is, after all, how the shell displays it.
Learning about farm animals from my niece
Things you don't learn in biology class.
How does a shell namespace extension provide icons for virtual items that track the standard icons set by the user’s file associations?
Forward to the standard implementation.
What happens if you call VirtualAlloc to MEM_COMMIT a page you never MEM_RESERVE?
It is not guaranteed to succeed.
How do we change permissions on a share as fast as Explorer does it?
First, make sure you're changing the permissions on a share.
First, try reading the error message, episode 4: Even programmers see error messages without reading them
Here we go again.
How do I obtain the comment for a share?
NetShareGetInfo.
Hacking the law: On the role of the marriage officiant in the State of Washington
Strange rules that basically mean there are no meaningful rules.
Calling ShutdownBlockReasonCreate from my service doesn’t stop the user from shutting down
That's not how to do it from a service.
If you can’t remember the exact text of a dialog box (so you can search for it), you can ask the Internet
Search ju-jitsu, v2.
Why can’t I create a file equal to the available disk space?
Gotta save the metadata somewhere.
The trust relationship between this workstation and the primary domain failed, what does this mean?
The secret password every machine has.
What happens to lost timer messages if I don’t process them fast enough?
They never existed.
Why doesn’t my keyboard hook get called for keyboard messages I manually posted?
Because that's not input.
How do I call SetTimer with a timer ID that is guaranteed not to conflict with any other timer ID?
Put it in its own window.
It rather involved being on the other side of this airtight hatchway: Elevation from Administrator to SYSTEM
But you're already there.
Thanks for informing us that you know about the compatibility issue in your application, so we don’t have to fix it
Now that you let us know that you know, you can deal with it yourself.
How can I tell if Windows Update is waiting for the system to reboot?
RebootRequired.
Why are there all these processes lingering near death, and what is keeping them alive?
Actually, they're zombies.
How can I start my service as soon as possible, before any other service?
FRIST!
Why doesn’t GetAddrInfo work from behind a proxy?
You can't get there from here.
A process inherits its environment from its parent, and the consequences of this simple statement
The chain of custody.
How do I run a Web search in the user’s default Web browser using their default search provider?
You kind of have to guess.
The C runtime library cannot be mixed and matched
Coupled to the compiler.
How do you get network connectivity from the worst PC in the world?
Can't use an expansion slot.
Raymond’s Windows Universal Samples API concordance
Finding samples that use a particular method or property or whatever.
Cynical interpretations of various project milestones
Call it what you want.
I guess this explains why Warren Buffett hasn’t retired
Hang in there.
Using an intermediate library to make the main library retargetable
A little traffic cop.
When I change the icon in my shortcut, why doesn’t it update on the screen?
Dotting all the i's.
I saved some files into the Program Files directory, and now they’re gone!
They got virtualized.
Microspeak: move the needle
Have a significant and noticeable impact
How do I enumerate remembered connections that are not currently connected?
WNetEnumResources again.
Debugging walkthrough: Access violation on nonsense instruction, episode 3
Ow, that patch hurts.
The Windows 95 I/O system assumed that if it wrote a byte, then it could read it back
Stands to reason.
Rules can exist not because there’s a problem, but in order to prevent future problems
Not constraining future optimizations.
Microspeak: DRI, the designated response individual
The first line of defense.
Insightful graph: The ship date predictor
Factor of two (and a little).
Handy delegate shortcut hides important details: The hidden delegate
Sit. Stay.
I saw a pinvoke signature that passed a UInt64 instead of a FILETIME, what’s up with that?
Stricter than necessary, but that's okay.
If you are going to call Marshal.GetLastWin32Error, the function whose error you’re retrieving had better be the one called most recently
Watch out for functions called behind your back.
If you are going to call Marshal.GetLastWin32Error, the function whose error you’re retrieving had better have SetLastError=true
Or it won't get anything.
p/invoke gotcha: C++ bool is not Win32 BOOLEAN is not UnmanagedType.Bool
Watch the sizes.
Windows started picking up the really big pieces of TerminateThread garbage on the sidewalk, but it’s still garbage on the sidewalk
So stop throwing garbage on the sidewalk.
Crashes in the I/O stack tend to occur in programs which do the most I/O
just playing the odds.
Why does the taskbar icon for grouped windows change to something weird?
Because you told it to use that icon.
The ARM processor architecture: Somebody else’s introduction
Over at the NT Debugging blog.
The changing fortunes of being the last program on the Start menu
Last but not least.
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?
The Application User Model ID strikes again.
The Itanium processor, part 10: Register rotation
Around and around.
The Itanium processor, part 9: Counted loops and loop pipelining
Line up in neat order.
The Itanium processor, part 8: Advanced loads
I hoped you were going to say that.
The Itanium processor, part 7: Speculative loads
I knew you were going to say that.
The Itanium processor, part 6: Calculating conditionals
Deciding what to do next.
The Itanium processor, part 5: The GP register, calling functions, and function pointers
Who am I? How did I get here?
The Itanium processor, part 3b: How does spilling actually work?
Working quietly in the background.
The Itanium processor, part 4: The Windows calling convention, leaf functions
Just use what you've got.
The Itanium processor, part 3: The Windows calling convention, how parameters are passed
Slide on over.
The Itanium processor, part 2: Instruction encoding, templates, and stops
Stop and go.
The Itanium processor, part 1: Warming up
All those registers.
The curse of the redefinition of the symbol HLOG
Too generic a name.
Corrupted file causes application to crash; is that a security vulnerability?
Maybe, maybe not.
When you think you found a problem with a function, make sure you’re actually calling the function, episode 2
Watch out for the local overrides.
Please enjoy the new eco-friendly printers, now arguably less eco-friendly
Missing the point.
How can I detect whether a keyboard is attached to the computer?
Look at the available raw input devices.
What did the Ignore button do in Windows 3.1 when an application encountered a general protection fault?
Muddling through.
Why do I get ERROR_INVALID_HANDLE from GetModuleFileNameEx when I know the process handle is valid?
Because it's not complaining about the process handle.
Why doesn’t the Print command appear when I select 20 files and right-click?
So you don't kill your machine with a stray click.
Hazy memories of the Windows 95 ship party
How'd that happen?
Generating different types of timestamps from quite a long way away
Transforming in reverse.
On the various ways of creating large files in NTFS
To zero or not to zero.
Why is my x64 process getting heap address above 4GB on Windows 8?
Why shouldn't it?
What would be the point of creating a product that can’t do its job?
No 32-bit server products. Because what would be the point?
Intentionally making the suggestion look nothing like any scripting language, yet understandable enough to get the point across
Pseudobabble.
Trying out all the different ways of recognizing different types of timestamps from quite a long way away
Running through the list.
Why does the BackupWrite function take a pointer to a modifiable buffer when it shouldn’t be modifying the buffer?
An artifact of an earlier time.
Is a SID with zero subauthorities a valid SID? It depends whom you ask
Maybe.
How secure are GUIDs? Can I use it to generate passwords?
Not a good idea.
2015 mid-year link clearance
Midpoint check.
Microspeak: Stretch goal
Extra credit.
Parsing a string as a 64-bit integer, somehow
Signed or unsigned, I don't care.
Windows 95 and Windows NT manage the TEB on x86 differently
Reuse.
Where is the full version of the music that plays when you start Windows 98 for the first time?
There isn't one.
A trick for finding the correct internal mailing list
Looking for common threads.
Sorry for the interruption, but it doesn’t happen often
Be right back.
Reinterpreting the bits of a 64-bit integer as if they were a double-precision floating point number (and vice versa)
Punning.
Random links on taking better pictures
Just a little linkery.
Why does the class name for Explorer change depending on whether you open it with /e?
Compatibility, of course.
How come the technique for launching an unelevated process from an elevated process doesn’t work?
You've disabled the feature that makes unelevated processes possible.
When you think you found a problem with a function, make sure you’re actually calling the function
Don't mock me.
One way to make sure nobody reports problems with your Web site
I'll get right on that.
How can I reposition my window so it isn’t covered by the touch keyboard?
Taking it a step further.
How can I force a CreateFile call to hang, in order to test something?
Opportunistic locks again.
Keep your eye on the code page: Is this string CP_ACP or UTF-8?
You don't know. Somebody has to tell you.
Taking ownership of a file doesn’t give you access, yet
One more step.
Bitter or acerbic? or does it make a difference?
What does that word mean?
How can I reposition my controls so they aren’t covered by the touch keyboard?
Register with the framework input pane.
There is no /8TB flag on 64-bit Windows
You get it all, baby.
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?)
You can get it without the name.
Adding a little marker to your comments in Microsoft Word
The TAB key.
Why do events logged by the ReportEvent function show up in the wrong order in the Event Viewer?
Bad sorting.
How can I make the touch keyboard appear automatically when focus enters an edit control in my program?
Enable focus tracking.
Under what conditions can SetFocus crash? Another debugging investigation
SetFocus is the symptom, not the cause.
When designing your user interface, be mindful of the selection-readers
Also the double-click readers, the hover-readers, and the margin-click readers.
Dubious security vulnerability: Luring somebody into your lair
Constructing an insecure directory.
The tadpole operators explained
Combining two things in an unintuitive way.
New C++ experimental feature: The tadpole operators
Give it a whirl.
So you decided to call SHFileOperation from a service, at least remember to disable copy hooks
Mitigating the disaster.
If you can set enforcement for a rule, you can set up lack of enforcement
An exeption to a rule is just another rule.
When you inadvertently become a collector of something you really aren't all that into
As I was heading home at the end of the day, I ran into one of my colleagues who was also going home, and he was carrying a Star Wars-themed metal lunchbox similar to this one. For those who didn't grow up in the United States, these metal lunchboxes are the type of things elementary school children use to carry their lunch to school. I remarked, "Nice lunchbox." My colleague explained, "Yeah, I sort of ended up as the lunchbox guy. It started when somebody gave me a lunchbox as a semi-humorous gift, and I kept it on my shelf. Then other people saw that I had a metal lunchbox and concluded, 'Oh, he must collec...
It rather involved being on the other side of this airtight hatchway: Code injection via QueueUserAPC
But you already pwn that thread.
Determining programmatically whether a file was built with LAA, ASLR, DEP, or OS-assisted /GS
Sucking the flags out of the header.
MapGenericMask is just a convenience function for converting generic access to specific access, according to the instructions you provide
It's useful on the server side, not the client side.
Low-level hooks have thread affinity, so make sure you keep an eye on the thread
Poof, it's gone.
Why don't you forward WM_GETMINMAXINFO and clamp the results?
In my illustration of how to make a window resizable in only one direction, commenter Josua asks, "Why don't you forward and clamp the results?" I'm going to assume the question is really "Why don't you forward before clamping the results?" rather than "Why did you bother writing all this code in the first place? Why not simply forward and clamp the results?"¹ The answer is that forwarding doesn't do anything. As noted in the documentation, the incoming structure already has the default values on entry. The default handler for the message returns without doing anything, since all the default handler...
How does Task Manager compute Up Time, and why doesn't it agree with GetTickCount?
Task Manager shows a piece of information called "Up time". How is this value calculated, and why doesn't it agree with the value reported by /? Task Manager calculates "up time" by subtracting the system boot time from the current time. In other words, it is misnamed; it really should be called time since system was started. It doesn't subtract out the time when the computer was in sleep or hibernation. The tick count, on the other hand, counts only time that elapses while the computer is on.
Can I run a service executable from a network location?
You can, but you shouldn't.
Documentation creates contract, which is why you need to be very careful what you document
Once it's documented, it needs to remain supported forever.
Hidden message in a T-shirt, it's been done before
While everybody is trying to figure out the hidden message in Joe Belfiore's T-shirt,¹ I figure I'd give you an easier puzzle. Here is the pattern of 0's and 1's printed on the T-shirt handed given out at the Windows 8 kick-off meeting. Because you don't have a project until you have a T-shirt. The actual shirt clipped many of the digits to make the shape come out smoother. I've filled in the partial digits. There are at least two typos in the shirt. It didn't take a room full of developers long to decode the message. Click here to reveal the answer. The digits are merely the binary encoding ...
Why is there an invisible U+202A at the start of my file name?
The desperation Left-to-right marker.
What does it mean when the Advanced Security Settings dialog says that an ACE was inherited from "Parent Object" without naming the specific parent?
The Advanced Security Settings dialog shows the ACEs in an object's ACL, and one of the pieces of information is a column labeled Inherited from which identifies whether the ACE was inherited, and if so, from where. A customer observed that when they opened the Advanced Security Settings dialog, one of their objects had an ACE that showed Parent Object as the Inherited from. However, when they went to the parent object , that ACE is nowhere to be found. How can an ACE be inherited from its parent, when it doesn't exist in the parent? The Advanced Security Settings dialog is trying to be helpful, but in...
Creating a window that can be resized in only one direction
Overriding WM_NCHITTEST.
That's not how you start a boat
Tomorrow is Opening Day of the Seattle boating season. (Which, as I noted some time ago, is purely a social occasion with no legal significance.) One of my colleagues is not much of a boat person, but his wife is. (In fact, she's a commercial fisherman.) They were on board some fancy boat or other as it sat docked. He was up on the top deck—this being a boat so fancy that it had an upstairs and a downstairs—and as the preparations were made for heading out, his wife called out to him to start the boat, since he's up there already. Now, as I mentioned, my colleague isn't much of a boat person. But h...
How does the window manager adjust ptMaxSize and ptMaxPosition for multiple monitors?
Very carefully.
How can I tell if a file is an image of some type?
The perceived type tells you what kind of file it is, for a very general sense of the word "kind".
Is the atom returned by RegisterClass(Ex) a "real" atom?
A customer was debugging some code that calls on a class that's already been registered. In this case, it was registered by another DLL in the same process. Normally, this wouldn't be a problem, because each DLL passes its own instance handle to so that there are no name collisions. However, in this case, both DLLs are passing the flag, which means that collisions can occur after all. The customer found that the call to , which makes sense in the case of a collision in the global class table. The code then calls to look up the class name, but fails, saying, "No such atom." Does this mean that the class at...
Access to a file's attributes is controlled by two things
We saw some time ago that permission to delete a file is granted either File attributes behave in an analogous way. Permission to read a file's attributes is granted either If you want the file's attributes, you could always get it by reading the directory, because one of the pieces of information you get from is the file attributes. Therefore, having permission to read a directory implicitly gives you permission to read the attributes of any file in that directory. (Note, of course, that write permission on attributes is another story.)
Wow, they really crammed a lot into those 410 transistors
Just an order of magnitude. Or three. Or more.
How do I extract the path to Control Panel from this shortcut so I can launch it?
You don't need to.
Why can't I have variadic COM methods?
COM methods cannot be variadic. Why not? Answer: Because the marshaler doesn't know when to stop. Suppose variadic COM methods were possible. And then you wrote this code: How would COM know how to marshal this function call? In other words, suppose that is a pointer to a proxy that refers to an object in another process. The COM marshaler needs to take all the parameters to , package them up, send them to the other process, then unpack the parameters, and pass them to the implementation. And then when the implementation returns, it needs to take the return value and any output parameters, package them u...
How did the scopes for the CryptProtectMemory function end up in a strange order?
Incremental functionality.
It rather involved being on the other side of this airtight hatchway: Invalid parameters from one security level crashing code at the same security level (yet again)
You never crossed the boundary.
What was the starting point for the Panther Win32 kernel?
That one started from Windows NT.
How to find the IP address of a hacker, according to CSI: Cyber
According to television.
Why are there both TMP and TEMP environment variables, and which one is right?
Parallel evolution.
Why did the original code for FIND.COM use lop as a label instead of loop?
An old puzzle.
When I set the "force X off" policy to Disabled, why doesn't it force X on?
A customer was using one of the many "force X off" policies, but instead of using it to force X off, they were trying to use it to force X on by setting the policy to Disabled. For example, there is a "Hide and disable all items on the desktop". The customer was setting this policy to Disabled, expecting it to force all icons visible on the desktop, removing the option on the desktop View menu to hide the icons. As we discussed some time ago, group policy is for modifying default behavior, and interpreting them requires you to have a degree in philosophy. In particular, a policy which forces X off has three st...
In the Seattle area, people treat you nicer once they learn your last name is Gates
Go figure.
After I encrypt memory with CryptProtectMemory, can I move it around?
Yes.
On the ways of creating a GUID that looks pretty
Don't just make up something. There are rules.
If more than one object causes a WaitForMultipleObjects to return, how do I find out about the other ones?
Just the one you are told about.
Why is the System.DateCreated property off by a few seconds?
Legacy time/date format.
The details of the major incident were not clearly articulated, but whatever it is, it's already over
When a server is taken offline, be it a planned unplanned outage or an unplanned unplanned outage or something else, the operations team send out a series of messages alerting customers to the issue. Some time ago, I received a notification that went like this: From: Adam Smith Subject: Nosebleed Service : Major Incident Notification - Initial Date: mm/dd/yyyy 1:16AM Major Incident Notification dfdsfsd Affected Users fdfsdfsdf Incident Duration: 1 hour 15 minutes Impact fsdfdsfsdf Continued Notifications fdsfsdf Information & Support Thank you, Adam Smith IT Major Incident Mana...
Opening the classic folder browser dialog with a specific folder preselected
Call me, honey.
Why is CreateToolhelp32Snapshot returning incorrect parent process IDs all of a sudden?
It was always incorrect, you just didn't know it.
It appears that some programmers think that Windows already ships with that time machine the Research division is working on
Make sure the object of your action exists before you try it.
Under what circumstances will a dialog box not use the caption specified in the resource file?
Who's changing it?
What was the relationship between Outlook and Outlook Express?
None.
I want you to chase your sisters until they throw up
Heaven for little boys.
How do I make a boldface item on a context menu?
The menu default item.
Flaw reported in Windows 95
And a note from Mom.
Switching on a tuple: Sneaky trick
Data packing.
What's the difference between PathIsSystemFolder and Protected Operating System Files?
The way to detect weird directories that should be excluded from the user interface is to check for the and attributes being set simultaneously. This is the mechanism used when you uncheck Hide protected operating system files in the Folder Options dialog. (Programmatically, you detect whether the user wants to see protected operating system files by checking the member of the structure.) Michael Dunn suggested using to detect these special directories, but that is not quite right. is for marking a directory as "This directory has a nondefault UI behavior attached to it. Please consult the file for mo...
A Venn diagram demonstrating the dining options in one of the new cafeterias
Spelling out the options.
CancelIoEx can cancel I/O on console input, which is kind of nice
Stop that input.
Finding the constructor by scanning memory for the vtable
Reversal of fortune.
Sure, we have RegisterWindowMessage and RegisterClipboardFormat, but where are DeregisterWindowMessage and DeregisterClipboardFormat?
It not going away.
Travel tip: Don't forget your car on the ferry
One of my colleagues lives on Bainbridge Island and has quite a long commute to work each day. From his house, he walks to the bus stop, then takes the bus to the Winslow ferry terminal, then takes the ferry to the Seattle ferry terminal, then takes the bus to Microsoft. And at the end of the day, he does the trip in reverse. One day, for whatever reason, he drove to work instead of taking the bus. He drove to the ferry terminal, took the ferry across, then drove to work. And at the end of the day, he drove to the ferry, but when the ferry arrived at its destination, he forgot that he had driven his car and wa...
Microspeak: Headcount, req, and related personnel terms
Jargon from the personnel side of the business.
Does the CLR really call CoInitializeEx on the first call to unmanaged code, even if you don't deal with COM at all and are just calling native code via p/invoke?
Some time ago, I called out this part of the documentation regarding managed and unmanaged threading: On the first call to unmanaged code, the runtime calls CoInitializeEx to initialize the COM apartment as either an MTA or an STA apartment. You can control the type of apartment created by setting the System.Threading.ApartmentState property on the thread to MTA, STA, or Unknown. Commenter T asks, "Does it do this even if you don't deal with COM at all and call native code through a P/Invoke?" Well, the documentation says it does, and we can confirm with an experiment: Run this program with...
Debugging walkthrough: Access violation on nonsense instruction, episode 2
Dueling debuggers.
Under what conditions will the IUnknown::AddRef method return 0?
When it's lying.
Dubious security vulnerability: Copying a program and running the copy
Code execution results in code execution.
The more times you use the word "simply" in your instructions, the more I suspect you don't know what that word means
I was helping somebody look up how to enable frobbing for widgets, and I found one set of instructions on a blog somewhere. To be honest, this happened long enough ago that I forgot what it was exactly, but here's something that captures the general spirit: First, check whether your widget supports frobbing. To do this, simply run this command where is the voodoo code for your widget. It will say "frob supported" if your widget supports frobbing. If you don't know your widget's voodoo code, you can get a list of the voodoo codes and enchantment numbers for all the widgets connected to your computer by s...
How can I programmatically resize a listview column to fit its contents?
ListView_SetColumnWidth.
A question about the FileTimeToLocalFileTime function turned out to be something else
Negative time.
Modifying the CS_NOCLOSE style does affect all windows of the class, just not necessarily in an immediately noticeable way
It's there, you just can't see it.
Why are the dimensions of a maximized window larger than the monitor?
So you don't see the borders.
Setting up a new computer often results in leftover slot covers, so what do you do with the slot covers?
Doorstop.
Connecting some blocks: Tell me more about the current image in my wallpaper slide show
Click.
Solving the problem rather than answering the question: How can a non-administrator modify a registry key that requires administrator permission?
Design so you don't need administrative privileges.
RegNotifyChangeKeyValue sucks less
No longer tied to a specific thread.
Why does the mouse cursor jump a few pixels if you click on the very bottom row of pixels on the taskbar?
Because that's where you wanted it to be.
Nice job, you got an A minus from Bill
That's as high as it goes.
Further adventures in trying to guess what encoding a file is in
Today's candidate: IMultiLanguage2::DetectCodepageInIStream
Non-capturing C++ lambdas can be converted to a pointer to function, but what about the calling convention?
Nothing to see, so nothing to pass.
What's the point of using a custom timer queue if there is a default one already?
A customer observed that when you create a timer via , you have the option of passing either to get the default timer queue or a handle to a custom timer queue created by the function. Why would you want to create a custom timer queue? If you create a custom timer queue, then you know that all the timers in the queue are yours. For example, there might be another component in the process that creates a lot of timers in the default timer queue. If you had put your timers in the default timer queue, then your timers will risk starvation. It's the same sort of logic that might lead you to create a custom heap in...
When asking about the capacity of a program, you also need to consider what happens when you decide to stop using the program
It'll fit as long as you need it.
Microspeak: Light up
Enabling functionality when available.
The 2015/2016 Seattle Symphony subscription season at a glance
The pocket reference guide for 2015/2016.
Reading the word under the cursor via UI Automation
Grab and go.
What is this inconsistent heap state that MSDN warns me about during DLL_PROCESS_DETACH?
Following through on consequences of TerminateThread.
Who is this rogue operative that filled my object with 0xDD, then sent me a message?
Not really dead.
Why was the replacement installer for recognized 16-bit installers itself a 32-bit program instead of a 64-bit program?
It's the right thing to do.
Staying cool is one of the skills of a corporate president
Didn't break a sweat.
Using thread pool cleanup groups to clean up many things at once
Take out the whole group.
Use GFlags to catch the silent killer (silent but deadly)
Silent Process Exit.
The SuspendThread function suspends a thread, but it does so asynchronously
Yes, I heard you, but I'm kind of busy right now.
If you wonder why a function can't be found, one thing to check is whether the function exists in the first place
One of my colleagues was frustrated trying to get some code to build. "Is there something strange about linking variadic functions? Because I keep getting an unresolved external error for the function, but if I move the function definition to the declaration point, then everything works fine." "With the above code, the linker complains that cannot be found. But if I move the implementation of to the top of the file, then everything builds fine." "I tried putting an explicit calling convention in the declaration, I tried using , nothing seems to help." We looked at the resulting object file and observed...
Another way to make sure nobody sends you feedback
Boing.
Customizing item enumeration with IShellItem, the old-fashioned way
Driving it manually.
Got errands? Now is the time
Everybody else is watching the game.
Creating a shared memory block that can grow in size
The SEC_RESERVE flag.
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
ClearType is a technology that blends text pixels with background pixels with the goal of reducing visual artifacts during text rendering.¹ If you go for the full-meal version of ClearType, it uses knowledge about the physical properties of LCD screens in order to carry out its work. Some time ago, I noted one catch with this model, which is that overdraw gives the ClearType algorithm the wrong background pixels. Another gotcha is that if you don't know what the background pixels are at all, then you can't use ClearType. For example, you might be rendering a semi-transparent bitmap that will be drawn on to...
The compiler can make up its own calling conventions, within limits
Global optimizations.
Tip for trying to boost morale: Don't brag about your overseas trips
Once upon a time, a senior manager held a team meeting to address low team morale. Attempting to highlight how important the project was, he opened by saying, "I just got back from 〈faraway country〉, meeting with some of our important clients, and..." This remark had exactly the opposite effect from what the manager intended. Instead of revitalizing the team, the team became even more despondent. "Here we are, working late and coming in on weekends, and this senior manager is telling us about his recent overseas junket." (After he left, I heard that he still pulled this stunt with his new team. "Over ...
Customizing item enumeration with IShellItem
Have it your way.
Helper functions to make shell bind contexts slightly more manageable
Setting the options.
The wonderful world of shell bind context strings
A generic options parameter.
Why does my synchronous overlapped ReadFile return FALSE when the end of the file is reached?
That's what the documentation says, in a way that could be made more clear.
Why does the copy dialog give me the incorrect total size of the files being copied?
It's all a misunderstanding.
Why does Outlook use a semicolon to separate multiple recipients by default?
In triplicate, please.
Why does a single integer assignment statement consume all of my CPU?
Alignment fixups.
Why does CreateFile take a long time on a volume handle?
Flush that volume.
Where can I find the standard asynchronous stream?
Not that sense of the word standard.
Microspeak: landing (redux)
Settled.
Limiting the bottom byte of an XMM register and clearing the other bytes
More SSE tweaking.
Finding the leaked object reference by scanning memory: Example
Digging through the haystack.
What happens if I don't pass a pCreateExParams to CreateFile2?
The final parameter to the function is optional. What happens if I pass ? If you pass as the parameter, then the function behaves as if you had passed a pointer to this structure:
Why is there a BSTR cache anyway?
It was useful, once.
No good deed goes unpunished: Marking a document as obsolete
Stop looking at me.
More notes on calculating constants in SSE registers
All at the top or bottom.
How do you prevent the linker from discarding a function you want to make available for debugging?
Put it outside the linker's knowledge.
Horrifically nasty gotcha: FindResource and FindResourceEx
The old switcheroo.
2014 year-end link clearance
Another round of the semi-annual link clearance.
Even the publishing department had its own Year 2000 preparedness plan
On December 31, 1999, Microsoft Product Support Services were ready in case something horrible happened as the calendar rolled over into the new year. I'm told that Microsoft Press also had its own Year 2000 plan. They staffed their helpline continuously from Friday evening December 31, 1999 all the way through Sunday, January 2, 2000. They did this even though Microsoft Press did not normally staff its helpline ouside normal business hours, and even though all sample code in all publications come with a disclaimer that they are provided "as is" with no warranty. I do not know if they took any calls, but I sus...
How did that program manage to pin itself to my taskbar when I installed it?
Occasionally, somebody will notice that upon installing a program, it managed to pin itself to the taskbar. But just like there is no function, there is also no function, and for the same reason: Because applications would abuse it and auto-pin themselves because they are so awesome, and so that the developer could get a nice bonus. In spite of these roadblocks, some applications manage to pin themselves to the taskbar anyway, typically by programmatically driving the shortcut context menu. The developer then collects their bonus and goes out and gets drunk. There is no real way of blocking this behavior ot...
Integer signum in SSE
The signum function is defined as follows: There are a couple of ways of calculating this in SSE integers. One way is to convert the C idiom The SSE translation of this is mostly straightforward. The quirk is that the SSE comparison functions return −1 to indicate , whereas C uses +1 to represent . But this is easy to take into account: Substituting this into the original function, we get In assembly: With intrinsics: This pattern extends mutatus mutandis to , , and . Another solution is to use the signed minimum and maximum opcodes, using the formula In assembly: With intrinsi...
Debugging walkthrough: Access violation on nonsense instruction
A colleague of mine asked for help puzzling out a mysterious crash dump which arrived via Windows Error Reporting. Well that's a pretty strange instruction. Especially since it doesn't match up with the source code at all. There is no bit-toggling in the actual code. The method calls to , , and are all interface calls and therefore should be vtable calls. We are clearly in a case of a bogus return address, possibly a stack smash (and therefore cause for concern from a security standpoint). My approach was to try to figure out what was happening just before the crash. And that meant figuring out how we ...
My pants are fancy!
During the development of Windows, the User Research team tried out an early build of some proposed changes on volunteers from the general community. During one of the tests, they invited the volunteer to just play around with a particular component, to explore it the way they would at home. The usability subject scrolled around a bit, admired the visuals, selected a few things, and then had an idea to try to customize the component. He fiddled around a bit and quickly discovered the customization feaure. To celebrate his success, he proudly announced in a sing-song sort of way, "My pants are fancy!" That cl...
How can I let my child use an app that I bought from the Windows Store?
If you buy an app from the Windows Store, you can make it available to other users on the same Windows PC. This is useful if you, say, buy an app for your child to use. Here's how you do it. (This is all explained on the Windows Store blog, but I've converted it into a step-by-step and updated it for Windows 8.1.) First, sign on as yourself and install the app under your own account. Next, sign on as the child (or whatever other account you want to share the app with), and launch the Store from that second account. In the Store app, go to the top of the screen and hit Account, then My account. From the My ac...
The Softsel Hot List for the week of December 22, 1986
Look at all that stuff people bought.
Setting, clearing, and testing a single bit in an SSE register
Today I'm going to set, clear, and test a single bit in an SSE register. Why? On Mondays I don't have to explain why. First, we use the trick from last time that lets us generate constants where all set bits are contiguous, and apply it to the case where we want only one bit. We start by setting all bits in . We then shift both 64-bit lanes right by 63 positions, putting 1 in each lane. If the bit we want is in the upper half, then we shift the entire value left 8 bytes (64 bits). This clears the bottom 64 bits and leaves the upper 64 bits with all bits set. (Similarly, if the bit we want is in the...
How did protected-mode 16-bit Windows fix up jumps to functions that got discarded?
Commenter Neil presumes that Windows 286 and later simply fixed up the movable entry table with jmp selector:offset instructions once and for all. It could have, but it went one step further. Recall that the point of the movable entry table is to provide a fixed location that always refers to a specific function, no matter where that function happens to be. This was necessary because real mode has no memory manager. But protected mode does have a memory manager. Why not let the memory manager do the work? That is, after all, its job. In protected-mode 16-bit Windows, the movable entry table was ignored....
How can I query the location of the taskbar on secondary monitors?
A customer wanted to know how to get the location of the taskbar on secondary monitors. "I know that will tell me the location of the taskbar on the primary monitor, but how do I get its location on secondary monitors?" We asked the customer what their actual problem is, where they think that determining the taskbar location on secondary monitors is the solution. The customer was kind enough to explain. Our application shows a small window, and sometimes users move it behind the taskbar. They then complain that they can't find it, and they have to move their taskbar out of the way in order to find it again. We...
It's not too late (okay maybe it's too late) to get this gift for the physicist who has everything
A LEGO set to measure Planck's constant.
It rather involved being on the other side of this airtight hatchway: Account vulnerable to Active Directory administrator
A security vulnerability report came in that went something like this: Disclosure of arbitrary data from any user An attacker can obtain arbitrary data from any user by means of the following steps: There's no point continuing, because the first step assumes that you are on the other side of the airtight hatchway. If you have compromised the domain controller, then you control the domain. From there, all the remaining steps are just piling on style points and cranking up the degree of difficulty. A much less roundabout attack is as follows: No, wait, I can make it even easier. You are the dom...
If you set up roaming profiles, you are expected to set up each machine identically, for the most part
A customer discovered the following behavior when they set up roaming user profiles on their domain. Consider two machines, 1 and 2. An application A is installed on machine 1, but not machine 2. A user with a roaming profile logs onto machine 1 and pins application A to the taskbar. That user then logs off of machine 1 and logs onto machine 2. Now things get interesting: The taskbar on machine 2 initially shows a white icon on the taskbar, representing the nonexistent application A. A short time later, that icon vanishes. When the user logs off of machine&n...
When corporate policies meet precision scientific equipment
One of my colleagues used to work as an IT consultant, and one of his clients was a tobacco company. Since they were a tobacco company, the company policy on smoking was "You can smoke anywhere, any time." "Anywhere" includes the labs. The labs with very expensive precision scientific equipment. My colleague told me that this policy meant that the company regularly replaced $50,000 pieces of equipment after only a few months, thanks to smoke damage. But the company couldn't change their smoking policy. Imagine the public relations disaster if a tobacco company had a no-smoking policy! Starting next year, cigar...
Notes on calculating constants in SSE registers
There are a few ways to load constants into SSE registers. Load them from memory. Load them from general purpose registers via . Insert selected bits from general purpose registers via . Try to calculate them in clever ways. Loading constants from memory incurs memory access penalties. Loading or inserting them from general purpose registers incurs cross-domain penalties. So let's see what we can do with clever calculations. The most obvious clever calculations are the ones for setting a register to all zeroes or all ones. These two idioms are special-cased in the processor and execute faster th...
Detecting whether a SID is well-known SID
You might think that the function would tell you whether a SID is well-known, but it doesn't. Rather, it tells you whether a SID exactly matches the well-known SID you specified. For example, you can ask, "Is this the Authenticated Users SID?" or "Is this the Everyone SID?" But you can't ask, "Is this any type of well-known SID?" I guess you could enumerate through all the well-known SIDs, and check if your SID matches any of them, but that's getting kind of ugly. If what you're interested in is whether this is a machine-relative SID (or a domain-relative SID, which is the special case where the machine is ...
What states are possible in a DRAWITEMSTRUCT structure?
The structure has an member which contains a number of bits describing the state of the item being drawn. How do those states map to the underlying control? Most of the states are rather obvious. For a list box item to be selected, it means that the item is part of the selection. But what does selected mean for a button? Since people like tables, I'll put the answer in a table: Okay, now that it's all in a table, how do I read the table? A box is blank if the corresponding flag is not currently used by the control type. (No guarantees about the future.) For example, as of this writing, button controls do ...
If you get a procedure address by ordinal, you had better be absolutely sure it's there, because the failure mode is usually indistinguishable from success
A customer reported that the function was behaving strangely. We have this code in one of our tests: Recently, this test started failing in bizarre ways. When we stepped through the code, we discovered that ends up calling instead of . The first time we try to test , we get stack corruption because has a different function prototype from , and of course on top of that the test fails horribly because it's calling the wrong function! When trying to narrow the problem, we found that the issue began when the test was run against a version of the DLL that was missing the function entirely. The line wa...
The psychology of confirmation, or something, I don't know what to call it
There is probably a name for this phenomenon. I will illustrate it below. "Is there a way to configure the system to do X?" — Go to the Y dialog and select Z. "It doesn't work." — I just tried it. It works for me. I'm using 〈configuration details〉. "Thanks. It's working."
Creating double-precision integer multiplication with a quad-precision result from single-precision multiplication with a double-precision result
Suppose you want to multiply two double-word values producing a quad-word result, but your processor supports only single-word multiplication with a double-word result. For concreteness, let's say that your processor supports 32 × 32 → 64 multiplication and you want to implement 64 × 64 → 128 multiplication. (Sound like any processor you know?) Oh boy, let's do some high school algebra. Let's start with unsigned multiplication. Let x = A × 2³² + B and y = C × 2³² + D, where A, B, C, and D are all in the range 0 … 2³² − 1. Each of the multiplications (not counting the power-of-two multiplications) is a 32 × 3...
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
Calling to cancel a window timer prevents messages from being generated for that timer, even if one is overdue. In other words, give this sequence of operations: no message is ever generated. Even though a timer became due during the , no timer message was generated during the sleep because timer messages are generated on demand, and nobody demanded one. Killing the timer then removes the ability to demand a timer message, and the result is that no message ever appears. In general, this means that once you kill a timer, you will not receive any messages for that timer. Unless you demanded one while ...
If my WM_TIMER handler takes longer than the timer period, will my queue fill up with WM_TIMER messages?
A customer was worried that they may have a problem with their message queue filling with messages. "If my handler takes longer than the timer period, will my queue fill up with messages?" As we should know by now, timer messages are generated on demand: The WM_TIMER message is a low-priority message. The GetMessage and PeekMessage functions post this message only when no other higher-priority messages are in the thread's message queue. Here's the basic algorithm. (I'm ignoring filtering and I'm assuming that messages are removed.) Notice that the generated messages are generated on demand ...
What happens if I don't paint when I get a WM_PAINT message?
Suppose your window procedure doesn't paint when it gets a message. What happens? It depends on how you don't paint. If you have an explicit handler for the message that does nothing but return without painting, then the window manager will turn around and put a new message in your queue. "And try harder this time." Remember that the rules for the message are that the window manager will generate a message for any window that has a dirty region. If you fail to remove the dirty region in your message handler, well, then the rules state that you get another message. (The most common way of clearing the ...
Microspeak: Redlines
To the outside world, redline can mean to mark something for removal, or it could mean the maximum safe speed of an engine. But in the world of Microsoft design, the term redlines (pronounced as if it were written as the two words red lines, but the accent is on the red) refers to a diagram showing the exact position of visual elements. They typically take the form of a proposed screen shot, with arrows and lines superimposed to indicate the distances between items, which items align with each other, and so on. They also contain indications as to the exact colors to use for different elements. Originally the li...
Counting array elements which are below a particular limit value using SSE
Some time ago, we looked at how doing something can be faster than not doing it. That is, we observed the non-classical effect of the branch predictor. I took the branch out of the inner loop, but let's see how much further I can push it. The trick I'll employ today is using SIMD in order to operate on multiple pieces of data simultaneously. Take the original program and replace the function with this one: Now, this program doesn't actually use any parallel operations, but it's our starting point. For each 32-bit value, we load it, compare it agains the boundary value, and accumulate the result. The func...
A user's SID can change, so make sure to check the SID history
It doesn't happen often, but a user's SID can change. For example, when I started at Microsoft, my account was in the SYS-WIN4 domain, which is where all the people on the Windows 95 team were placed. At some point, that domain was retired, and my account moved to the REDMOND domain. We saw some time ago that the format of a user SID is The issuing entity for a local account on a machine is the machine to which the account belongs. The issuing entity for a domain account is the domain. If an account moves between domains, the issuing entity changes, which means that the old SID is not valid. A new SID...
Some light reading on lock-free programming
Today is a holiday in the United States, so I'm going to celebrate by referring you to other things to read. I'm going to start with a presentation by Bruce Dawson at GDC 2009, which is basically multiple instances of the question "Is this code correct?", and the answer is always "No!" Although the title of the talk is Lockless Programming in Games, the information is relevant to pretty much everybody. I can't find a recording of the presentation, but you can download the PowerPoint slides or view them in your browser. But I recommend downloading the PowerPoint slides and reading the notes, because the notes e...
If 16-bit Windows had a single input queue, how did you debug applications on it?
After learning about the bad things that happened if you synchronized your application's input queue with its debugger, commenter kme wonders how debugging worked in 16-bit Windows, since 16-bit Windows didn't have asynchronous input? In 16-bit Windows, all applications shared the same input queue, which means you were permanently in the situation described in the original article, where the application and its debugger (and everything else) shared an input queue and therefore would constantly deadlock. The solution to UI deadlocks is to make sure the debugger doesn't have any UI. At the most basic level, the ...
What is the difference between Full Windows Touch Support and Limited Touch Support?
In the System control panel and in the PC Info section of the PC & Devices section of PC Settings, your device's pen and touch support can be reported in a variety of ways. Here is the matrix: The meaning of No touch and Single touch are clear, but if a device supports multiple touch points, what makes the system report it as having Limited versus Full touch support? A device with Full touch support is one that has passed Touch Hardware Quality Assurance (THQA). You can read about the Windows Touch Test Lab (WTTL) to see some of the requirements for full touch support. If you have a touch device without ...
The crazy world of stripping diacritics
Today's Little Program strips diacritics from a Unicode string. Why? Hey, I said that Little Programs require little to no motivation. It might come in handy in a spam filter, since it was popular, at least for a time, to put random accent marks on spam subject lines in order to sneak past keyword filters. (It doesn't seem to be popular any more.) This is basically a C-ization of the C# code originally written by Michael Kaplan. Don't forget to read the follow-up discussion that notes that this can result in strange results. First, let's create our dialog box. Note that I intentionally give it a huge font ...
Is it wrong to call SHFileOperation from a service? Revised
My initial reaction to this question was to say, "I don't know if I'd call it wrong, but I'd call it highly inadvisable." I'd like to revise my guidance. It's flat-out wrong, at least in the case where you call it while impersonating. The registry key is bound to the current user at the time the key is first accessed by a process: The mapping between HKEY_CURRENT_USER and HKEY_USERS is per process and is established the first time the process references HKEY_CURRENT_USER. The mapping is based on the security context of the first thread to reference HKEY_CURRENT_USER. If this security context does not have a...
A library loaded via LOAD_LIBRARY_AS_DATAFILE (or similar flags) doesn't get to play in any reindeer module games
If you load a library with the flag, then it isn't really loaded in any normal sense. In fact, it's kept completely off the books. If you load a library with the , , or flag (or any similar flag added in the future), then the library gets mapped into the process address space, but it is not a true module. Functions like , , and will not see the library, because it was never entered into the database of loaded modules. These "load library as..." flags don't actually load the library in any meaningful sense. They just take the file and map it into memory manually without updating any module tracking databases...
Distinguishing between normative and positive statements to help people answer your question
Often, we get questions from a customer that use the word should in an ambiguous way: Our program creates a widget whose flux capacitor should have reverse polarity. Attached is a sample program that shows how we create the widget with . However, the resulting widget still has a flux capacitor with standard polarity. Can you help us? The phrase should have reverse polarity is ambiguous. The question could be We would like to create a widget whose flux capacitor has reverse polarity. Attached is a sample program that shows how to create a widget whose flux capacitor has standard polarity. How should we modify...
File version information does not appear in the property sheet for some files
A customer reported that file version information does not appear on the Details page of the property sheet which appears when you right-click the file and select Properties. They reported that the problem began in Windows 7. The reason that the file version information was not appearing is that the file's extension was . Older versions of Windows attempted to extract file version information for all files regardless of type. I believe it was Windows Vista that changed this behavior and extracted version information only for known file types for Win32 modules, specifically , , , , , and . If the file's ex...
How do I enumerate drives the same way that the NET USE command does?
If you use the Remote Desktop Connection client to connect to another computer, you have the option of making your local drives available to the remote computer. A customer wanted to know how to enumerate all the drives on the local machine. The were able to get the volumes mapped to drive letters, but they also wanted to get the redirected drives injected by Terminal Services. (Mind you, these aren't volumes that are assigned drive letters, so it's not clear why they are interested in them, but whatever.) With the command, they see the Terminal Services volumes in Explorer, and they can be browsed via : ...
How to view the stack of a user-mode thread when its kernel stack has been paged out
Suppose you have a machine that has crashed, and your investigation shows that the reason is that there is a critical section that everybody is waiting for. While waiting for that critical section, work piles up, and eventually the machine keels over. Suppose further that this crash is given to you in the form of a kernel debugger. In case it wasn't obvious, by "you" I mean "me". Okay, so the critical section that is the cause of the logjam is this one: "Great," you say. "I just need to look at thread 0x4228 to see why it is stuck. Woo-hoo, there's the thread. Now I just need to switch to its context ...
When does GetTickCount consider the system to have started?
The and functions return "the number of milliseconds that have elapsed since the system was started." (The 32-bit version wraps around after around 50 days.) But when exactly is the system considered to have started? Is it when power is applied to the computer? When the BIOS completes POST? When the user picks the operating system from the boot menu? When the kernel switches to protected mode? It isn't defined exactly when the timer starts. Because that's not its purpose. The purpose of is to let you measure intervals of time. It provides a common clock source so that multiple components can coordinate their...
How can I wait until all startup applications have finished launching?
A customer wanted to know how to detect that all startup applications have finished launching. They wanted to wait until everything settled down before proceeding with some task. What if two programs did this? Suppose two programs both wanted to detect that all startup applications have finished launching. Each one would sit there waiting for the other, because this is one of those I want to be the last to do something, even laster than the other guy who wants to do something last things. If you want to wait until the system is idle to perform some task, you can use the Task Scheduler to create an idle-time t...
A little cheat in my Tiger Beat photo homage
One thing nobody has called out in my tribute to the Bill Gates Tiger Beat photo, either because it was too subtle or too obvious, is that the photo is actually a mirror image. The arrangement of furniture in the room was not correct: The big table was on the wrong side of the room. It was also too heavy to move around, so we cheated. We staged the entire picture as a mirror image, flipping the Windows screen shot. And then back in the virtual darkroom, Ariel flipped the photo to put the furniture on the correct side of the photo. Here are the clues in the photo: Chatter: The day after I put this article in...
Kicking around a function that formats stuff
Today's "Little Program" is really a "Little Puzzle" that got out of hand. This started out as a practical question: This code fragment screams out for some sort of simplification. (I've changed the names of the classes.) Clearly, the pattern is Everything here is pretty straightforward, except for the part. Can we write a function that takes a and formats it in a somewhat flexible manner? Let's start with the -and- cases. We might try something like this: But then we'd run into trouble, because there is no constraint on , so the compiler will complain, "I don't know how to get a or a from an ."...
Why does an attempt to create a SysLink control in my plug-in sometimes fail?
A customer had written a plug-in for some application, and they found that their plug-in was unable to create a SysLink control via the function. The same code in a standalone application works fine, but when the code is placed in their plug-in, the code fails. Debugging showed that the call to succeeded, but the call failed with "Cannot find window class." The customer is another victim of not keeping their eye on the activation context. They attached a manifest to their DLL so that the call to maps to the version of the common controls library that supports the SysLink control. But they did nothing to e...
Raymond, why did you stop studying Chinese? It has no grammar!
It does; you just don't realize it.
How do I get a handle to the primary monitor?
There are various ways of getting a monitor. You can get the monitor from a point, from a rectangle, or from a window. But how do you get the primary monitor? The primary monitor is defined to be the one which has (0, 0) as its origin. Therefore, one solution is The desktop window by convention is deemed to reside primarily on the primary monitor, so you could also use this: Or you could just pass the null window handle. This is technically an illegal parameter, but by specifying , you are saying, "If anything goes wrong, give me the primary monitor." In this case, we are intentionally going astray b...
Passing the incorrect object type for a handle, how bad is it?
A customer asked a somewhat strange question: "We are calling but passing the handle to a waitable timer. Application Verifier reports, "Incorrect object type for handle." But the code works well. We want to know the risks of passing the wrong object type to . Is the recommendation only to pass handles of type "Event" to ? Let's answer those questions in reverse order. Yes, the recommendation is only to pass handles of type "Event" to , just as the recommendation is only to pass handles of type "Semaphore" to , and more generally, only to pass valid parameters to functions. What is the risk of passing the wro...
Microspeak: Line of sight
I first encountered this term in a meeting I attended. Q: We would like to be able to reverse the polarity of the neutron flow without requiring a reboot. A: Yes, that is something we've been thinking about, but we don't have line of sight to having that feature before the end of the month. From context, having line of sight to a result means something like "Have made it part of our immediate plans to achieve that result." This appears to be extending the idiom on the horizon. Literally, something on the horizon. is at the edge of what can be seen. Figuratively, then, something that is on the horizon is a...
Applying a filter to the contents of an Explorer Browser
Today's Little Program hosts an Explorer Browser but filters the contents to remove DLL files. You can, of course, substitute your own filter. (For example, maybe you want to show only files that changed since the last time the user ran your program, or you might want a view of My Computer but filtered to show only removable drives.) Remember that Little Programs do little to no error checking, and they don't necessarily demonstrate the best programming style. They're just quick demonstrations. Today's smart pointer library is… (rolls dice) … WRL! Start with our minimal explorer browser progra...
The case of the file that won't copy because of an Invalid Handle error message
A customer reported that they had a file that was "haunted" on their machine: Explorer was unable to copy the file. If you did a copy/paste, the copy dialog displayed an error. Okay, time to roll up your sleeves and get to work. This investigation took several hours, but you'll be able to read it in ten minutes because I'm deleting all the dead ends and red herrings, and because I'm skipping over a lot of horrible grunt work, like tracing a variable in memory backward in time to see where it came from.¹ The Invalid file handle error was most likely coming from the error code . Some tracing of ha...
Why is the FAT driver called FASTFAT? Why would anybody ever write SLOWFAT?
Anon is interested in why the FAT driver is called FASTFAT.SYS. "Was there an earlier slower FAT driver? What could you possibly get so wrong with a FAT implementation that it needed to be chucked out?" The old FAT driver probably had a boring name like, um, FAT.SYS. At some point, somebody decided to write a newer, faster one, so they called it FASTFAT. And the name stuck. As for what you could possibly get so wrong with a FAT implementation that it needed to be improved: Remember that circumstances change over time. A design that works well under one set of conditions may start to buckle when placed under al...
The contents of the Start page are not programmatically accessible
A customer wanted to know if is possible for an application to edit the user's Start page. No, there is no interface for editing the user's Start page or even knowing what is on it. The Start page is the user's personal space and applications should not be messing with it. Imagine if it were possible. Every application would edit the Start page to put themselves at the front! It turns out that the customer wanted their application to make some changes to the user's Start page when it was installed. Specifically, they wanted to hunt down tiles belonging to their competitors and delete them, then insert a tile f...
A question about preventing the system from going to the idle state turns out to be misguided
A customer asked how they could have their program prevent the system from going to the idle state. Specifically, when the system goes idle, the application gets into a weird state where it starts leaking memory like crazy. The program normally uses around 100MB of memory, but when the system goes idle, something funky happens and the program's memory usage shoots up to 4GB. To avoid this problem, they want to prevent the system from entering the idle state. Now, if your application is a special-purpose program running on a dedicated computer, then blocking the entry into the idle state might be acceptable. Aft...
Enumerating the ways of distributing n balls into k boxes
Suppose you had n indistinguishable balls and k distinguishable boxes. Enumerate the ways of distributing the balls into boxes. Some boxes may be empty. We can represent each distribution in the form of n stars and k − 1 vertical lines. The stars represent balls, and the vertical lines divide the balls into boxes. For example, here are the possible distributions for n = 3, k = 3: This visualization is known in combinatorics circles as stars and bars. From this visualization, we see that what we are doing is taking n + k − 1 slots, and in each slot placing a star or a bar, subject to the const...
Debugging a hang: Chasing the wait chain inside a process
Today we're going to debug a hang. Here are some of the (redacted) stacks of the process. I left some red herrings and other frustrations. Since debugging is an exercise in optimism, let's ignore the stacks that didn't come out properly. If we can't make any headway, we can try to fix them, but let's be hopeful that the stacks that are good will provide enough information. Generally speaking, the deeper the stack, the more interesting it is, because uninteresting threads tend to be hanging out in their message loop or event loop, whereas interesting threads are busy doing something and have a complex stack ...
How can I detect programmatically whether the /3GB switch is enabled?
A customer was doing some diagnostic work and wanted a way to detect whether the switch was enabled. (Remember that the switch is meaningful only for 32-bit versions of Windows.) The way to detect the setting is to call and look at the . Compile this as a 32-bit program and run it. On 32-bit systems, this reports the system-wide setting that specifies the maximum user-mode address space, regardless of how your application is marked. Note, however, that your application must be marked in order to take advantage of the space above 2GB. On the other hand, when you run a 32-bit application on 64-bit Wi...
How do I disable Windows 8 touch contact visualizations for my application?
You might have an application (like a game) where the default touch contact visualizations are a distraction. In WinRT, you can disable the contact visualizations by simply saying In Win32, you use the function. To demonstrate that, let's take our scratch program and make this simple change: The touch visualizations are white and the default window color is white, so the visualizations are hard to see in the scratch program. Let's change the color to something that the visualizations will be more visible against. Run the program, and you'll see that if you touch the window and drag your finger around,...
The great thing about regular expression languages is that there are so many to choose from!
Before you ask a question about regular expressions, you should make sure you and your audience agree on which regular expression language you are talking about. Here is a handy table of which features are supported by which regular expression language. You can use that table to solve this customer's problem: I have a regular expression that works just fine when I test it in 〈insert regular expression testing tool, like RegExr or RegexPlanet〉, but I can't get it to work in real life. My goal is to find all lines that contain an not followed anywhere by a .
Scripting an Internet Explorer window
Today's Little Program takes a random walk through MSDN by starting at the page and randomly clicking links. The exercise is not as important as the technique it demonstrates. (I'm assuming the reader can figure out what language this script is written in. If you have to ask, then you probably won't understand this article at all. I am also not concerned with random number bias because Little Program.) To talk a random walk through MSDN, we ask for all the links in the element. Note that I'm taking an undocumented dependency on the structure of MSDN pages. This structure has changed in the past, so be awa...
When are global objects constructed and destructed by Visual C++?
Today we're going to fill in the following chart: The C++ language specification provides some leeway to implementations on when global static objects are constructed. It can construct the object before begins, or it construct the object on demand according to complicated rules. You can read [basic.start.init] for the gory details. Let's assume for the sake of discussion that global static objects are constructed before begins. For global objects in the EXE, constructing them is no big deal because the C runtime startup code linked into the EXE does a bunch of preparation before calling the formal entry...
If only DLLs can get DllMain notifications, how can an EXE receive a notification when a thread is created (for example)?
When a DLL is loaded, it receives a notification, and when it is unloaded (or when the process terminates), it gets a notification. DLLs also receive notifications when a thread is created and notifications when a thread exits. But what if you are an EXE? EXEs don't have a , so there is no way to receive these notifications. The trick here is to hire a lackey. Create a helper DLL, called, say, . Your EXE links to the lackey, and the lackey's job is to forward all notifications back to your EXE. The DLL would naturally have to have a way for your EXE to provide the callback address, so you might have a f...
The GetCurrentThread function is like a check payable to Bearer: What it means depends on who's holding it
The function returns a pseudo-handle to the current thread. The documentation goes into significant detail on what this means, but I fear that it may have fallen into the trap of providing so much documentation that people decide to skip it. Okay, so first of all, what is a pseudo-handle? a pseudo-handle is a sentinel value for that is not really a handle, but it can act like one. The pseudo-handle returned by means, "The thread that this code is running on." Note that this is a context-sensitive proposition. All the text in MSDN is explaining the consequences of that sentence. In a sense, the functi...
Is there a way to disable a specific balloon notification without disabling all of them?
There is a group policy called Turn off all balloon notifications, but what if you want to turn off only one specific notification? The taskbar does not offer fine-grained policy control over balloon notifications. All you have is the giant sledgehammer that turns off all of them. If there is a specific balloon you want to disable, you have to check with the specific program that is raising them, or the specific product feature, to see if it offers a way to turn the balloon off. For example, there is a setting to disable the low disk space checks and another one to disable notifications that tell you when you...
Enumerating notification icons via UI Automation
Walking the tree.
Some parts of an interface can change but others can't
When I wrote about asking the compiler to answer calling convention questions, some people were concerned about whether this was a reliable mechanism or whether it was relying on something that can change in the future. This is a special case of the question, "What parts of an interface can change, and what can't?" And it all boils down to compile-time versus run-time. Assuming you are interested in binary compatibility (as opposed to merely source compatibility), then a decision made at compile-time can never be changed because the decision is already hard-coded into the application. For example, if you ha...
Why is there a 64KB no-man's land near the end of the user-mode address space?
We learned some time ago that there is a 64KB no-man's land near the 2GB boundary to accommodate a quirk of the Alpha AXP processor architecture. But that's not the only reason why it's there. The no-man's land near the 2GB boundary is useful even on x86 processors because it simplifies parameter validation at the boundary between user mode and kernel mode by taking out a special case. If the 64KB zone did not exist, then somebody could pass a buffer that straddles the 2GB boundary, and the kernel mode validation layer would have to detect that unusual condition and reject the buffer. By having a guaranteed in...
Standard handles are really meant for single-threaded programs
When I discussed the conventions for managing standard handles, Sven2 noted that I implied that you need to call with a new handle if you close the current handle and asked "Wouldn't it make more sense to call it the other way round? I.e., first set the new handle, then close the old one? It would ensure that any other thread that runs in parallel won't get an invalid handle." Yes, that would make more sense, but only by a little bit. If you have one thread changing a standard handle at the same time another thread tries to use it, you still have the race condition, as Cesar noted, where the thread that gets ...
Microspeak: All-up
In other words: All-inclusive.
Enumerating cyclical decompositions with Stirling numbers
This whole enumeration nightmare-miniseries started off with Stirling numbers of the second kind. But what about Stirling numbers of the first kind? Those things ain't gonna enumerate themselves! The traditional formulation of the recursion for Stirling numbers of the first kind (unsigned version, since it's hard to enumerate negative numbers) goes like this: c(n + 1, k) = n · c(n, k) + c(n, k − 1). although it is more convenient from a programming standpoint to rewrite it as c(n, k) = (n − 1) · c(n − 1, k) + c(n − 1, k − 1). The Wikipedia article explains ...
Why is 0x00400000 the default base address for an executable?
Rewind to 1987.
In the red corner, EXCEPTION_INT_DIVIDE_BY_ZERO and STATUS_INTEGER_DIVIDE_BY_ZERO; and in the blue corner, EXCEPTION_INT_OVERFLOW and STATUS_INTEGER_OVERFLOW
The exception code (and its doppelgänger ) is raised, naturally enough, when the denominator of an integer division is zero. The x86 and x64 processors also raise this exception when you divide by , or more generally, when the result of a division does not fit in the destination. The division instructions for those processors take a 2N-bit dividend and an N-bit divisor, and they produce N-bit quotient and remainder. Values of N can be 8, 16, and 32; the 64-bit processors also support 64. And the division can be signed or unsigned. Therefore, you can get this exception if you try to divide, say, 2³&s...
You can name your car, and you can name your kernel objects, but there is a qualitative difference between the two
A customer reported that the appeared to be unreliable. We have two threads, one that waits on an event and the other that signals the event. But we found that sometimes, signaling the event does not wake up the waiting thread. We have to signal it twice. What are the conditions under which will ignore a signal? // cleanup and error checking elided for expository purposes void Thread1() { // Create an auto-reset event, initially unsignaled HANDLE eventHandle = CreateEvent(NULL, FALSE, FALSE, TEXT("MyEvent")); // Kick off the background thread and give it the handle CreateThread(..., Thread2, event...
Why does misdetected Unicode text tend to show up as Chinese characters?
Do the math.
Simulating media controller buttons like Play and Pause
Today's Little Program simulates pressing the Play/Pause button on your fancy keyboard. This might be useful if you want to write a program that converts some other input (say, gesture detection) into media controller events. One way of doing this is to take advantage of the function, since the default behavior for the message is to pass the message up the parent chain, and if it still can't find a handler, it hands the message to the shell for global processing. Remember, don't fumble around. If you want to send a message to a window, then send a message to a window. Don't broadcast a message to every wi...
Marshaling won't get in your way if it isn't needed
I left an exercise at the end of last week's article: "Why is the error raised only sometimes?" COM subscribes to the principle that if no marshaling is needed, then an interface pointer points directly at the object with no COM code in between. If the current thread is running in a single-threaded apartment, and it creates a COM object with thread affinity (also known as an "apartment-model object"; yes, the name is confusing), then the thread gets a pointer directly to the object. When you call , you are calling directly into the implementation provided by the object. This principle has its pluses and mi...
If a process crashes while holding a mutex, why is its ownership magically transferred to another process?
A customer was observing strange mutex ownership behavior. They had two processes that used a mutex to coordinate access to some shared resource. When the first process crashed while owning the mutex, they found that the second process somehow magically gained ownership of that mutex. Specifically, when the first process crashed, the second process could take the mutex, but when it released the mutex, the mutex was still not released. They discovered that in order to release the mutex, the second process had to call twice. It's as if the claim on the mutex from the crashed process was secretly transferred to th...
What is the story of the mysterious DS_RECURSE dialog style?
There are a few references to the dialog style scattered throughout MSDN, and they are all of the form "Don't use it." But if you look in your copy of , there is no sign of anywhere. This obviously makes it trivial to avoid using it because you couldn't use it even if you wanted it, seeing as it doesn't exist. "Do not push the red button on the control panel!" — There is no red button on the control panel. "Well, that makes it easy not to push it." As with many of these types of stories, the answer is rather mundane. When nested dialogs were added to Windows 95, the flag to indicate that a dial...
The grand ambition of giving your project the code name Highlander
There can be only one, but will it be you?
Receiving a notification any time the selection changes in an Explorer window
Today's Little Program merely prints a message whenever the user changes the selection on the desktop. I chose the desktop for expediency, since it saves me the trouble of coming up with a way for the user to specify which Explorer window they want to track. Also, all I do is print a message saying "Selection changed!"; actually getting the selection was covered earlier in both C++ and script. Remember that Little Programs do little to no error checking. Our simply prints the message whenever it receives a event. Sure, this program isn't useful on its own, but you can incorporate into a program that ...
I marked my parameter as [optional], so why do I get an RPC error when I pass NULL?
Not that kind of optional.
The stream pointer position in IDataObject::GetData and IDataObject::GetDataHere is significant
An oft-overlooked detail of the and methods is the position of the stream pointer when the result is a stream. These rules are buried in the documentation, so I'm going to call them out louder. Let's look at first. If returns a stream, then the stream pointer must be positioned at the end of the stream before the stream is returned. In other words, the last thing you do before returning the stream is seek it to the end. The contents of the data object are assumed to extend from the start of the stream to the stream's position as returned by . (And no, I don't know why this rule exists.) I messed this ...
The citizenship test is pass/fail; there’s no blue ribbon for acing it
Six out of ten is all you need.
Poor man's comments: Inserting text that has no effect into a configuration file
Consider a program which has a configuration file, but the configuration file format does not have provisions for comments. Maybe the program has a "list of authorized users", where each line takes the form or , where is a group or user. For example, suppose we have that goes like this: This is the sort of file that can really use comments because people are going to want to know things like "Why does Bob have access?" One way of doing this is to embed the comments in the configuration file in a way that has no net effect. You can do this to add separator lines, too. Assuming that you don't have any u...
Microspeak: spend
Remember, Microspeak is not merely for jargon exclusive to Microsoft, but it's jargon you need to know. We don't encounter the term spend much in the engineering side of the company, but it's in common use among those who regularly deal with money and budgets. We are in line with company standards with regard to spend for this type of event. Q4 spend will be higher as a result of widget recolorization. Our corresponding spend will increase significantly if we adopt this proposal. From the above citations, it is apparent that the word spend is shorthand for expenditure. And then there's this citation: I'...
Enumerating all the ways of making change
Today's Little Program enumerates all the ways of making change for a particular amount given a set of available denominations. The algorithm is straightforward. To make change for a specific amount from a set of available denominations, you can take one denomination and decide how many of those you want to use. Then use the remaining denominations to make change for the remainder. For example, if the available coins have values [1, 5, 10, 25] and you want to make change for 60 cents, you first decide how many 25-cent pieces you want to use. If you use none, then you need to make change for 60 cents using ju...
What did Windows 3.1 do when you hit Ctrl+Alt+Del?
Figuring out what is messed up.
A lie repeated often enough becomes the truth: The continuing saga of the Windows 3.1 blue screen of death (which, by the way, was never called that)
Not quite Truthiness, but getting close.
The history of Win32 critical sections so far
The structure has gone through a lot of changes since its introduction back oh so many decades ago. The amazing thing is that as long as you stick to the documented API, your code is completely unaffected. Initially, the critical section object had an owner field to keep track of which thread entered the critical section, if any. It also had a lock count to keep track of how many times the owner thread entered the critical section, so that the critical section would be released when the matching number of calls was made. And there was an auto-reset event used to manage contention. We'll look more at that eve...
I wrote the original blue screen of death, sort of
It was blue, but it wasn't completely deadly.
Steve Ballmer did not write the text for the blue screen of death
Mixing up different dialog screens, all blue in color.
The wisdom of seventh graders: The emergency survival kit
As a precursor to reading a story about survival, seventh grade students were asked to come up with a list of things they would want to have in their emergency survival kit. Students were specifically instructed to limit themselves to things that were readily available (so no Apache helicopters), and the complete kit had to be something you could comfortably carry in a student backpack. As always, there are students who chose a very sensible collection of things to put in their emergency survival kit: water purification tablets, a flashlight (with batteries), a first-aid kit. Those students are not the subject ...
Piping to notepad
In honor of NotepadConf's new KickStarter video, today's Little Program takes its stdin and puts it in a Notepad window. The comments pretty much lay out the steps. The part that may not be obvious is the part that deals with UI Automation: We take the main Notepad window, then ask UI Automation to find Document element inside it. From that element, we extract the window handle, then drop to Win32 and send a message to jam the text into the Notepad window. If you save this program under the name , then you can do and it will open a Notepad window with a directory listing inside it. Change one line...
You can use a file as a synchronization object, too
A customer was looking for a synchronization object that had the following properties: Can be placed in a memory-mapped file. Can be used by multiple processes simultaneously. Bonus if it can even be used by different machines simultaneously. Does not leak resources if the file is deleted. It turns out there is already a synchronization object for this, and you've been staring at it the whole time: The file. File locking is a very old feature that most people consider old and busted because it's just one of those dorky things designed for those clunky database systems that use tape drives like they hav...
Aha, I have found a flaw in the logic to detect whether my program is running on 64-bit Windows
Some time ago, I described how to detect programmatically whether you are running on 64-bit Windows, and one of the steps of the algorithm was "If you are a 64-bit program, then you are running on 64-bit Windows, because 32-bit Windows cannot run 64-bit programs." Every so often, somebody will claim that they found a flaw in this logic: "This algorithm may work today, but it assumes that the only version of Windows that can run 64-bit applications is 64-bit Windows. What if a future non-64-bit version of version of Windows runs 64-bit applications? Then your algorithm will incorrectly say that it is running on...
Why does the timestamp of a file increase by up to 2 seconds when I copy it to a USB thumb drive?
We saw some time ago that the FAT file system records timestamps in local time to only two-second resolution. This means that copying a file to a FAT-formatted device (typically a floppy drive or a USB thumb drive) can increase the timestamp by up two seconds. And even after the file is copied, the timestamp is not stable. The timestamp changes depending on the time zone employed by the computer that accesses the drive. In particular, if you are in a part of the world which changes clocks during the summer, then the timestamp on the file moves by an hour every spring and then moves in the opposite direction ev...
Who wrote the text for the Ctrl+Alt+Del dialog in Windows 3.1?
Steve.
It’s a trap! Employment documents that require you to violate company policy
Required to commit actions that are grounds for termination.
How can I detect that a user's SID has changed and recover their old data?
A customer maintained a database which recorded information per user. The information in the database is keyed by the user's SID. This works out great most of the time, but there are cases in which a user's SID can change. "Wait, I thought SIDs don't change." While it's true that SIDs don't change, it is also true that the SID associated with a user can change. Since SIDs encode the domain to which they belong, a user which moves from one domain to another within an organization, will need to be assigned a new SID. But wait, does that mean that the user lost access to all their stuff? After all, all their stu...
Taking advantage of the fact that the handle returned when you create a kernel synchronization object has full access regardless of the actual ACL
A customer wanted some help deciding what security attributes to place on an event object intended to be used by multiple security contexts. We have two processes, call them A and B, running in different security contexts. I have an event that process A creates and shares with process B. The only thing process A does with the event is signal it, and the only thing process B does with the event is wait on it. Our question is what ACLs you recommend for the event. For now, we're using O:BAD:(A;;GR;;;WD)(A;;GA;;;LS)(A;;GA;;;BA). (In case it matters, process A is usually running as a service with Local System priv...
Where does the Installed Updates control panel get the install date from?
A corporate customer wanted to know where the Installed Updates control panel gets the Installed On information from, because they found that the values were always set to the current date regardless of when the update was actually installed. The algorithm goes roughly like this: First, ask MSI what date the update was installed by calling and asking for the . If that doesn't work, then go to the registry key under and look for a value called (surprise) . (Note that 32-bit updates on 64-bit machines will be redirected into a key.) If that still doesn't work, then it's time to guess: Windows XP uses th...
It's time we face reality, my friends: We're not rocket scientists
During the development of Windows 95, it was common for team members to pay visits to other teams to touch base and let them know what's been happening on the Windows 95 side of the project. It was during one of these informal visits that the one of my colleagues reported that he saw that one of the members of the partner team had a Gary Larson cartoon from The Far Side depicting a group of scientists studying a multi-stage rocket ship they just assembled, but the stages are connected all crooked. One of the scientists says, "It's time we face reality, my friends. … We're not exactly rocket s...
How do I read the "Double-click to open an item (single-click to select)" setting in Folder Options?
Today's Little Program reports whether the Double-click to open an item (single-click to select) option is selected in the Folder Options dialog. A customer wanted to know how to do this, presumably so that their program would respect the setting and adjust its user interface to match. The flag and member name is kind of weird. The ability to single-click to open an item was introduced as part of the Windows Desktop Update which came with Internet Explorer 4. This update made Explorer more Web-like, with single-click to activate and underlines appearing on hover. (This was back in the day when making eve...
Dispelling the myths, rumors, and innuendo surrounding the QueryPerformanceCounter function
The function has been the subject of much rumor and innuendo. In response to all the confusion, the kernel folks put together a page which tries to settle the controversy once and for all. It discusses the history of QPC over the ages, the problems it had on earlier versions of Windows or older firmware (which is probably where a lot of the myths started), its interaction with hypervisors, offers guidance on how to use it and its alternatives, and includes a very nice Q&A.
Why does the OpenThread function behave differently when the target thread belongs to another process?
A customer discovered strange behavior in the function and wondered whether it was expected. We use the function to obtain a thread handle with , passing in a valid thread ID. We later pass this handle to to get the thread exit code. We have found that the function succeeds if the thread in question belongs to another process, provided the thread is still running (has not yet exited). On the other hand, if the thread belongs to our own process, then the call always succeeds regardless of whether the thread is running or not. Is this expected behavior? And can we assume that if fails with , then it means that...
Some reasons not to do anything scary in your DllMain, part 3
In the same week, the shell team was asked to investigate two failures. The first one was a deadlock in Explorer. The participating threads look like this: The shell extension caused this problem because it ignored the rule against calling shell and COM functions from the entry point, as specifically called out in the documentation as examples of functions that should not be called. The authors of this shell extension may never have caught this problem in their internal testing (or if they did they didn't understand what it meant) because hitting this deadlock requires that a race window be hit: The shell ...
If you're looking for the code that displays a particular dialog box, the most directly way to find it is to look for the dialog box
Suppose you are working in a large or unfamiliar code base and you want to know where the code is that displays a particular dialog box or message box or something. Probably the most direct way of figuring this out is to look for the strings. Say there is a message box that asks for user confirmation. "Are you sure you want to frobulate the flux capacitor?" Search for that string in your source code. It will probably be in a resource file. Great, now you have the string ID for that message. You can perform a second search for that ID. If the thing you are searching for is a dialog box or menu item, then ...
My friend and his buddy invented the online shopping cart back in 1994
Back in 1994 or so, my friend helped out his buddy who worked as the IT department for a local Seattle company known as Sub Pop Records. Here's what their Web site looked like back then. Oh, and in case you were wondering, when I said that his buddy worked as the IT department, I mean that the IT department consisted of one guy, namely him. And this wasn't even his real job. His main job was as their payroll guy; he just did their IT because he happened to know a little bit about computers. (If you asked him, he'd say that his main job was as a band member in Earth.) The mission was to make it possible for fan...
News flash: Big houses cost more to maintain
In 2005, we learned that big houses cost more to heat. In 2006, we learned that big houses cost more to cool. But then the research into big houses seems to have stalled. No worries. The research journal The Wall Street Journal recently released a paper concluding that big houses cost more to maintain.
Deleting elements from an JavaScript array and closing up the gaps
Today's Little Program is an exercise that solves the following problem: Given a JavaScript array and an unsorted array (possibly containing duplicates), calculate the result of deleting all of the elements from the original array as specified by the indices. For example, suppose and . The indices specify that elements 2 (charles), 4 (eve), 2 (charles again, redundant), and 0 (alice) should be deleted from the array, leaving bob and david. Now, if you had to delete only one element from the array, it is pretty simple: The trick with removing multiple elements is that deleting one element shifts th...
The scope of the C# checked/unchecked keyword is static, not dynamic
C# has operators and to control the behavior of the language in the face of integer overflow. There are also and statements which apply the behavior to blocks of statements rather than single expressions. Why, then, doesn't this code below raise an overflow exception? (Mini-exercise: Why couldn't I have just written ?) The answer is that the scope of the or keyword is static, not dynamic. Whether a particular arithmetic is checked or unchecked is determined at compile time, not at run time. Since the multiplication in the function is not explicitly marked checked or unchecked, uses the overflow co...
Customers not getting the widgets they paid for if they click too fast -or- In C#, the += operator is not merely not guaranteed to be atomic, it is guaranteed not to be atomic
In the C# language, operation/assignment such as are explicitly not atomic. But you already knew this, at least for properties. Recall that properties are syntactic sugar for method calls. A property declaration is internally converted to the equivalent of Accessing a property is similarly transformed. Note that the only operations you can provide for properties are and . There is no way of customizing any other operations, like . Therefore, if you write the compiler has no choice but to convert it to If all you have is a hammer, everything needs to be converted to a nail. Since the read and w...
Keep your eye on the code page: C# edition (the mysterious third code page)
A customer was having trouble manipulating the console from a C# program: We found that C# can read only ASCII data from the console. If we try to read non-ASCII data, we get garbage. Observe that this program is unable to read the Å and ö characters. They come back as garbage. Although there are three code pages that have special treatment in Windows, the CLR gives access to only two of them via . CharSet.Ansi = CP_ACP CharSet.Unicode = Unicode (which in Windows means UTF16-LE unless otherwise indicated). Unfortunately, the console traditionally uses the OEM code page. Since the ...
Keep your eye on the code page: C# edition (warning about DllImport)
Often, we receive problem reports from customers who failed to keep their eye on the code page. Does the function support files with non-ASCII characters in their names? We find that the function either fails outright or returns question marks when asked to provide information for files with non-ASCII characters in their name. If we ask for the display name, the function fails even though the file does exist. If we also pass the flag to force the system to act as if the file existed, then it returns the file name but with question marks where the non-ASCII characters should be. The function supports ...
Revival of the Daleks: Act One, Scene One
In 2009, a group of volunteers on a routine cleanup of a pond in Hampshire, England discovered a Dalek. (Later in the episode, the story may introduce a scientist who is thawing out a 30,000-year-old-virus.)
If you want to set a thread's apartment model via Thread.CurrentThread.ApartmentState, you need to act quickly
Welcome to CLR Week 2014. Don't worry, it'll be over in a few days. A customer wanted to know why their was displaying the infamous Current thread must be set to single thread apartment (STA) mode before OLE calls can be made error. "Even though we set the to , the apartment state is still . Curiously, if we put the above code in a standalone test program, it works fine." The problem is that the customer is changing the apartment state too late. On the first call to unmanaged code, the runtime calls CoInitializeEx to initialize the COM apartment as either an MTA or an STA apartment. You can...
The case of the orphaned LpdrLoaderLock critical section
A customer found that under heavy load, their application would occasionally hang. Debugging the hang shows that everybody was waiting for the critical section. The catch was that the critical section was reported as locked, but the owner thread did not exist. How can a critical section be owned by thread that no longer exists? There are two ways this can happen. One is that there is a bug in the code that manages the critical section such that there is some code path that takes the critical section but forgets to release it. This is unlikely to be the case for the loader lock (since a lot of really smart ...
The latest technologies in plaintext editing: NotepadConf
On November 13, 2014 November 14, 2014, Saint Paul, Minnesota will be the home to NotepadConf, which bills itself as "the premier technology conference for Notepad.exe users and text enthusiasts." I'm still not sure whom Microsoft will send to the conference, but maybe that person could give a talk on how you can use Notepad to take down the entire Internet. Update: The conference has been rescheduled to Friday the 14th.
Since clean-up functions can't fail, you have to soldier on
Clean-up functions can't fail, so what do you do if you encounter a failure in your clean-up function? You have to keep cleaning up. Some people like to follow this pattern for error checking: And some like to put it inside a cute flow control macro like or even Whatever floats your boat. But you have to be careful if using this pattern in a clean-up function, because you might end up not actually cleaning up. For example: What if there is an error disconnecting the doodad? (Maybe you got because the doodad lives on a remote server which crashed.) The cleanup code treats this as an error and...
Why does Explorer say "File too large" for my custom file system, when the problem has nothing to do with the file being too large (heck it's not even a file)
When Explorer copies files around, it doesn't really know what the maximum file size supported by any file system happens to be. (That information is not reported by .) So it guesses. If the file system name is or , then Explorer assumes that the maximum file size is 4GB − 1. Also, if a file operation fails with the error , and Explorer can't figure out why the parameter is invalid, it assumes that the reason is that the file has exceeded the maximum allowed file size. Why does Explorer map "invalid parameter" to "file size too large"? Because some file systems use to report that a file is too large in...
Microspeak: 1 – 1 is not zero
In his reddit AMA, Joe Belfiore wrote i have regular 1-1 meetings with my counterparts in Office, Skype, Xbox. The little bit of jargon there is 1-1 meeting. This is an abbreviation for one-on-one meeting, a common business practice wherein two people, typically a manager and a direct report, have a face-to-face meeting with no one else present. In the case Joe used, the meeting is not between a manager and a direct report but between two peers. The term is also abbreviated 1:1, which like 1 − 1 also looks like a bit of mathematical nonsense. But it's not zero or one. It's just an abbreviation for bu...
Enumerating the ways of choosing teams in a group of players
Suppose you have a bunch of people, and you want to break them up into m teams of size n. (Therefore you have a total of nm people.) Today's Little Program will enumerate the ways this can be done. Formally, let's say that you have a collection of size nm, and you want to enumerate the ways of partitioning the collection into m subsets, each subset of size n. The order of elements within each subset does not matter, and the order of the subsets doesn't matter. That's saying that a team of Alice and Bob is the same as a team of Bob and Alice, and Alice-Bob versus Charlie-David is the same as Charlie-David versu...
Before claiming that a function doesn't work, you should check what you're passing to it and what it returns
Before claiming that a function doesn't work, you should check what you're passing to it and what it returns, because it may be that the function is behaving just fine and the problem is elsewhere. The function does not appear to support directories with Unicode characters in their names. The correct directory name is obtained if it contains only ASCII characters in its name, but it truncates the string at the first non-ASCII character. If you step through the code in the debugger, you'll see that the function is working just fine. The buffer is filled with the current directory, including the non-ASC...
What is the strange garbage-looking string in the "command" value of a static verb?
A customer from a major software vendor asked, "What is the significance of the value that can be found under . It appears to be a copy of the default value, but with the program name replaced with apparent garbage. We've seen this both with Microsoft products as well as products by other companies. There is no mention of this value in the documentation on static verbs." The customer didn't explain why they were interested in this particular registry value. Maybe they thought it was enabling some super magical powers, and they wanted to get in on that action. (If that was the case, then they failed to noti...
If you want to be notified when your app is uninstalled, you can do that from your uninstaller
A customer had a rather strange request. "Is there a way to be notified when the user uninstalls any program from Programs and Features (formerly known as Add and Remove Programs)?" They didn't explain what they wanted to do this for, and we immediately got suspicious. It sounds like the customer is trying to do something user-hostile, like seeing that a user uninstalled a program and immediately reinstalling it. (Sort of the reverse of force-uninstalling all your competitors.) The customer failed to take into account that there are many ways of uninstalling an application that do not involve navigating to the...
Did the Windows 95 interface have a code name?
Commenter kinokijuf wonders whether the Windows 95 interface had a code name. Nope. We called it "the new shell" while it was under preliminary development, and when it got enabled in the builds, we just called it "the shell." (Explorer originally was named Cabinet, unrelated to the container file format of the same name. This original name lingers in the window class: CabinetWClass.)
Finding the shortest path to the ground while avoiding obstacles
Today's Little Program solves the following problem: Consider a two-dimensional board, tall and narrow. Into the board are nailed a number of horizontal obstacles. Place a water faucet at the top of the board and turn it on. The water will dribble down, and when it hits an obstacle, some of the water will go left and some will go right. The goal is to find the shortest path to the ground from a given starting position, counting both horizontal and vertical distance traveled. ⬤ • • • • • • • • • • &bu...
How do I obtain the computer manufacturer's name from C++?
Some time ago, I gave a scripting solution to the problem of obtaining the computer manufacturer and model. But what if you want to do this from C++? I could translate the script into C++, or I could just point you to Creating a WMI Application Using C++ in MSDN. In particular, one of the WMI C++ Sample Applications does exactly what you want: Example: Creating a WMI Application. The only things you need to do are
When I send a WM_GETFONT message to a window, why don't I get a font?
A customer reported that the message was not working. Specifically, they sent the message to a window, and they can plainly see that the window is rendering with a particular font, yet the message returns 0. Why isn't the window returning the correct font handle? The and messages are not mandatory. A window may choose to support them, or it may choose not to, or it may even choose to support one but not the other. (Though if it supports , it probably ought to support .) For example, our scroll bar program creates a custom font for the items in the list, but it does not implement the or messages. If you t...
When will GetSystemWindowsDirectory return something different from GetWindowsDirectory?
Most of the time, the returns the Windows directory. However, as noted in the documentation for : With Terminal Services, the GetSystemWindowsDirectory function retrieves the path of the system Windows directory, while the GetWindowsDirectory function retrieves the path of a Windows directory that is private for each user. On a single-user system, GetSystemWindowsDirectory is the same as GetWindowsDirectory. What's going on here, and how do I test this scenario? When Terminal Services support was being added to Windows NT 4.0 in the mid 1990's, the Termi...
Microspeak: Tell Mode / Ask Mode
As a product nears release, the rate of change slows down, and along the way, the ship room goes through stages known as Tell Mode and Ask Mode. In Tell Mode, any changes to the product do not require prior approval, but you are required to present your changes to the next ship room meeting and be prepared to explain and defend them. The purpose of this exercise is to get teams accustomed to the idea of having to present their changes to the ship room as a warm-up for Ask Mode. There is also the psychological aspect: If you have to present and defend your changes, you are going to be more careful about deciding ...
The alternate story of the time one of my colleagues debugged a line-of-business application for a package delivery service
Some people objected to the length, the structure, the metaphors, the speculation, and fabrication. So let's say they were my editors. Here's what the article might have looked like, had I taken their recommendations. (Some recommendations were to text that was also recommended cut. I applied the recommendations before cutting; the cuts are in gray.) You tell me whether you like the original or the edited version.
How can I get the URL to the Web page the clipboard was copied from?
When you copy content from a Web page to the clipboard and then paste it into OneNote, OneNote pastes the content but also annotates it "Pasted from ...". How does OneNote know where the content was copied from? As noted in the documentation for the HTML clipboard format, Web browsers can provide an optional property to specify the Web page the HTML was copied from. Let's write a Little Program that mimics what OneNote does, but just in plain text, because I don't want to try to parse HTML. This is much easier to do in C#, because the BCL provides most of the helper functions. First, we get the text fro...
The time one of my colleagues debugged a line-of-business application for a package delivery service
Back in the days of Windows 95 development, one of my colleagues debugged a line-of-business application for a major delivery service. This was a program that the company gave to its top-tier high-volume customers, so that they could place and track their orders directly. And by directly, I mean that the program dialed the modem (since that was how computers communicated with each other back then) to contact the delivery service's mainframe (it was all mainframes back then) and upload the new orders and download the status of existing orders.¹ Version 1.0 of the application had a notorious bug: Ninet...
Outdoor Trek: Mirror, Mirror starts this weekend
As previously noted, Outdoor Trek will be staging live performances of the Star Trek episode Mirror, Mirror. The schedule is up. Three weekends starting this Saturday at Blanche Lavizzo Park. Saturday performances are 7pm; Sunday performances are 2pm. Admission is free. Attend if you dare.
What does it mean when GetQueuedCompletionStatus return ERROR_SEM_TIMEOUT?
A customer asked for assistance interpreting a failure of the function. We are observing that is intermittently behaving as follows: That's all the information we have in our log files. We don't know the value of or , sorry. We realize that this is a rather vague question, but when this problem hits our machines, it causes our internal logic to go into a reset state since it doesn't know what the error means or how to recover. Resetting is expensive, and we would prefer to handle this error in a less drastic manner, if only we knew what it meant. The error code is a rather bad translation of the un...
How do I configure Windows Update programmatically?
First of all, normal programs shouldn't be messing with Windows Update configuration. That's something the user (or the user's administrator) decides. If you're an IT administrator, then you can use Group Policy to configure Windows Update on your network. But maybe you're a special case where the above remarks don't apply. Say you're a data center and all the systems are running inside of virtual machines and you don't want them installing updates or rebooting without your permission, so you want to run a script when you set up the image to disable updates. You can use the object, known to native code as ...
Why does Outlook map Ctrl+F to Forward instead of Find, like all right-thinking programs?
A feature request.
Enumerating integer compositions (the return of the binomial coefficients)
In number theory, a composition of an integer is an ordered sequence of positive integers which sum to the target value. For example, the value 3 can be written as 3, 1+2, 2+1, or 1+1+1. You can think about the target number as a string of stars, and a composition is a way of breaking the stars into groups. For example, here are the compositions of 3: How would you generate all compositions of a particular length? In the above example, the compositions of length 2 would be 1+2 and 2+1. Let's take a look at the last star in the composition. If it is immediately preceded by a space, then removing it results i...
If I duplicate a handle, can I keep using the duplicate after closing the original?
A customer asked whether it was okay to use a duplicated handle even after the original handle was closed. Yes. That's sort of why you would duplicate it. Duplicating a handle creates a second handle which refers to the same underlying object as the original. Once that's done, the two handles are completely equivalent. There's no way to know which was the original and which is the duplicate. Either handle can be used to access the underlying object, and the underlying object is not torn down until all handles to it have been closed. One tricky bit here is that since you have two ways to refer to the same thing...
Using the REFIID/void** pattern for returning COM objects for future-proofing and to avoid problems with dependencies
Suppose you have a function that creates a reference to a COM object: There are a few issues with this design. First of all, it requires that whoever uses your header file must have included first, since that's where is defined. You could solve that problem by putting at the top of , but that creates its own problems. For example, many header files alter their behavior based on symbols that have been d, and including that other header file as part of means that it's going to use the settings that were active at the time was included (which may not be what the clients of your header file are expecting)....
Why are only some of the Windows 7 system notification icons colorless?
Diminishing returns.
How do I turn off email reminders for my Windows Live calendar, and disable the birthday calendar while I'm at it?
You have to find the right check box.
Customing the standard color-picker dialog
A custom template, or possibly a custom hook function.
Communication between moving vehicles during the narrow window of the late 1990s
The long holiday weekend in the United States means that there are probably going to be a lot of people on road trips. Back in the old days before mobile phones, if you had multiple cars traveling together on a long trip, you had to stay within visible range of each other so that you didn't get separated. And if the car at the end of the convoy needed to pull over to take a bathroom break or something, they needed to rush to the front of the group and pantomime through the window to the passengers in the lead car to tell them what they were going to do, and then everybody would pull over together. I still remem...
It rather involved being on the other side of this airtight hatchway: Surreptitious file access by administrator
A security report was received that went something like this: A user can bypass file sharing locks by opening a read-only handle to the physical volume containing the file in question. This allows the user to extract the contents of protected files by reading the corresponding sectors directly from the disk. Since this operation requires administrator access, any user with administrator access can extract data from files that are normally inaccessible due to file locks, such as the SAM database. Yes, that's right. An attacker who gains administrator privileges can extract data from any file on the computer. B...
Redirecting the Favorites folder is technically legal, but you wouldn't like it
A customer liaison asked for assistance in debugging why Internet Explorer frequently stops responding at their customer's site. "We have tried a number of things like clearning the temporary Internet files, disabling add-ons, and resetting Internet Explorer settings. Please let me know if you can provide guidance based on the dump files provided below to indicate what could be causing Internet Explorer to hang here." The dump file showed 23 threads, and all of them seemed to be normal, except for one which looked like this: (Remember, you can get symbols for operating system binaries.) General debuggin...
What is the default size of the Recycle Bin, and how can an administrator control the size of the Recycle Bin?
A customer was setting up a file server to which they intended to redirect all their employees' documents. They were concerned about the amount of disk space used by all the Recycle Bins on that server. Is there a fixed default size for the Recycle Bin, or is it based on the size of the disk? Is there a way we can change the default size for the Recycle Bin? The customer is concerned that a user with a small quota on a large drive may end up filling their quota with Recycle Bin content and have no space left for their documents. For example, suppose you have a 1TB drive and each user has a 15 GB quota...
2014 mid-year link clearance
Another round of the semi-annual link clearance. James Mickens section January 2014: This World of Ours I have seen a video called “Gigantic Martian Insect Party,” and I have seen another video called “Gigantic Martian Insect Party 2: Don’t Tell Mom,” and I hated both videos, but this did not stop me from directing the sequel “Gigantic Martian Insect Party Into Darkness.” March 2014: To Wash It All Away Clearing the cache to fix a Web browser is like when your dad was driving you to kindergarten, and the car started to smoke, and he tried to fix the car by bangi...
Getting the location of the Close button in the title bar, from Windows 2000 or Windows XP
Today's Little Program locates the × button in the corner of the window and displays a balloon tip pointing at it. We did this some time ago with the help of the message, which is new for Windows Vista. But what if you don't have that message available, say, because you're running on Windows 2000 or Windows XP or (gasp) Windows 98? You can use the classic Accessibility interface to enumerate the buttons in the title bar and see which one the window reports as the Close button. Let's take the program from last time and change the function: We obtain the interface for the title bar and ...
Undefined behavior can result in time travel (among other things, but time travel is the funkiest)
The rules of logic no longer apply when you cross the line.
For Honor, For Excellence, For Pizza
Hacker News member citizenlow recalls the time I went over after hours to help out the Money team debug a nasty kernel issue. They were running into mysterious crashes during their stress testing and asked for my help in debugging it. I helped out other teams quite a bit, like writing a new version of Dr. Watson for the Windows 98 team or writing a new version of the MSConfig tool based on a sketch on a bar napkin. And for a time, I followed the official policy for moonlighting to make sure everybody understood that I was doing work outside the boundaries of my official job duties. When the Money folks ...
Getting past the question to solving the problem, episode 2014.06.25
Today is another example where the right thing to do is not to answer the customer's question but rather to solve the customer's problem. A customer liaison asked, "What do the registry keys X and Y do? We noticed that they are both read from and written to when you open a common file dialog. Just curious." I replied, "I'm curious as to your curiousity. I'm afraid that you are curious because your customer is curious, and then the customer will start relying on the keys in a strange and unsupported way." The format of those keys has varied from one version of Windows to another, so there is nothing there applic...
The social interactions in two preschool classes, in graphic form
Each preschooler at my daughter's school was asked a few simple questions, and the answers were printed in the yearbook. Among other things, the preschoolers were asked to complete the sentence, "I like to play with (person)." This is the type of question that leads to tears and hurt feelings. Whatever. Their parents are going to be stuck with the therapy bills. (My daughter is not a preschooler at the school, so I avoided a therapy bill. At least not over this.) From this data, I created a graph. Each arrow points from a student to the person they said they like to play with. This class breaks up into four ...
Finding the "Run as administrator" command, a game of hide-and-seek
Back in the old days, the "Run as administrator" menu option was placed on the extended menu. To get the extended menu, you hold the shift key when you right-click on the shortcut. In Windows 7, the "Run as administrator" option was moved to the primary menu, so you no longer need to hold the shift key to get it. Well, except that sometimes you still need to hold the shift key. The deal is that there are two "Run as administrator" commands. One of them is for running shortcuts to regular applications as administrator. The other is for running shortcuts to MSI applications as administrator. Shortcuts to M...
Adding a sound to the Alt+Tab window
Today's Little Program plays a sound when the Alt+Tab window appears and disappears. The program registers an accessibility event hook for the and events. The Start event fires when an Alt+Tab operation begins, and the End event fires when an Alt+Tab operation completes. As noted in the documentation, you can get spurious End events, so we keep track of our current state to avoid any surprises. In addition to adding an annoying sound to the Alt+Tab window, let's also add an annoying sound each time you move focus to a new item. Okay, this was a pretty annoying program, but maybe you can use it for som...
Once you go input-idle, your application is deemed ready to receive DDE messages
Feel free to stop using DDE. There was one customer who confessed that they were still using DDE, and they asked for help debugging a DDE problem. They found that sometimes, when their application was launched for DDE, it never received the message. Instead, the function returned . If launched from Explorer, the error message shown to the user was "There was a problem sending the command to the program." It took a long time to figure out what was going on, and there were a number of dead ends, but I'll cut to the chase: The problem was that one of the features they added to their program included code that r...
What happened to the Shut Down menu in classic Task Manager?
The great thing about open comments is that anybody can use them to introduce their favorite gripe as long as it shares at least four letters of the alphabet in common with the putative topic of the base article. xpclient "asks" why the Shut Down menu was removed from Task Manager. I put the word "asks" in quotation marks, because it's really a complaint disguised as a question. As in "Why do you guys suck?" The first thing to understand is that classic Task Manager went into a state of sustained engineering since Windows 2000. In other words, the component is there, but there is no serious interest in i...
10 is the new 6
While it may no longer be true that everything at Microsoft is built using various flavors of Visual C++ 5.0, 6.0, and 7.0, there is still a kernel of truth in it: A lot of customers are still using Visual C++ 6.0. That's why the unofficial slogan for Visual C++ 2010 was 10 is the new 6. Everybody on the team got a T-shirt with the slogan (because you don't have a product until you have a T-shirt).
Who would ever write a multi-threaded GUI program?
During the development of Windows 95, the user interface team discovered that a component provided by another team didn't work well under multi-threaded conditions. It was documented that the function had to be the first call made by a thread into the component. The user interface team discovered that if one thread called , and then used the component, then everything worked great. But if a second thread called , the component crashed whenever the second thread tried to use it. The user interface team reported this bug back to the team that provided the component, and some time later, an updated version o...
Enumerating bit strings with a specific number of bits set (binomial coefficients strike again)
Today's Little Program prints all bit strings of length n subject to the requirement that the string have exactly k 1-bits. For example, all bit strings of length 4 with 2 bits set are 0011, 0101, 0110, 1001, 1010, and 1100. Let's write BitString(n, k) to mean all the bit strings of length n with exactly k bits set. Let's look at the last bit of a typical member of BitString(n, k). If it is a zero, then removing it leaves a string one bit shorter but with the same number of bits set. Conversely every BitString(n − 1, k) string can be extended to a BitString(n, k) string by adding a zero to the end. ...
Non-classical processor behavior: How doing something can be faster than not doing it
Consider the following program: The program generates a lot of random integers in the range 0..9 and then counts how many are less than 0, less than 1, less than 2, and so on. It also prints how long the operation took in QPC units. We don't really care how big a QPC unit is; we're just interested in the relative values. (We print the number of items found merely to verify that the result is close to the expected value of .) Here are the results: To the untrained eye, this chart is strange. Here's the naïve analysis: When the boundary is zero, there is no incrementing at all, so the entire running...
Can we continue to call FindNextFile() with the same handle that returned an error last time?
A customer wanted to know whether it was okay to call with the same handle that returned an error last time. In other words, consider the following sequence of events: The customer elaborated: Suppose that the directory contains four files, A, B, C, and D. We expect the following: After returns an error, can we continue to search with the same handle? Or should we close the handle and get a new one from ? If it depends on the type of error that occurred, the customer would like to know more details about when the search can be continued and when it cannot. We asked the customer what problem they're ...
Why do network servers sometimes show up as a Recycle Bin Location?
A customer wanted to know why some of their users showed network servers among the locations shown in the Recycle Bin property sheet. Answer: Because those users are using Folder Redirection. In particular, if you redirect the My Documents folder, then a network Recycle Bin location is created to hold the files deleted from My Documents. The Recycle Bin folder in the user interface shows the union of all the recycled files in the individual Recycle Bin locations.
Microspeak: Brownbag
Remember, Microspeak is not merely for jargon exclusive to Microsoft, but it's jargon that you need to know. The term brownbag (always one word, accent on the first syllable) refers to a presentation given during lunch. The attendees are expected to bring their lunch to the meeting room and eat while they listen to the presentation. A brownbag could be a one-off presentation, or it could be a regular event. The speaker could be an invited guest, or the presenters may come from within the team. In general, the purpose of a brownbag is to familiarize the audience with a new concept or to share information with th...
Improving the performance of CF_HDROP by providing file attribute information
The clipboard format is still quite popular, despite its limitation of being limited to files. You can't use it to represent virtual content, for example. For all of you still using , you can improve the performance of drag/drop operations by adding a little more information to your data object. Observe that the clipboard format is just a list of paths. Some drop targets care about whether the paths refer to directories or to files, and since does not provide this information, the drop targets are forced to access the disk to get the answer. (This can be expensive for network locations.) To help this c...
Link-time code generation invalidates a lot of classical assumptions about linking
It goes beyond special relativity, beyond general relativity... into TIME TRAVEL.
Closing over the loop variable is just as harmful in JavaScript as it is in C#, and more cumbersome to fix
Prerequisite reading: Closing over the loop variable considered harmful. JavaScript has the same problem. Consider: The most common case where you encounter this is when you are hooking up event handlers in a loop, so that's the case I used as an example. No matter which button you click, they all alert , rather than the respective button number. The reason for this is given in the prerequisite reading: You closed over the loop variable, so by the time the function actually executed, the variable had the value , since that's the leftover value after the loop is complete. The cumbersome part is fixing...
Why did it take so long for Windows to support a taskbar on more than one monitor?
Mark wants to know why Windows has never supported having a taskbar on more than one monitor. (The question was asked before Windows 8 multi-monitor taskbar support became publically-known.) The feature has always been on the list, but it's a long list, and specifically the cost of designing, implementing, testing, performing usability tests, then redesigning the feature (because you will definitely need to redesign something as significant as this at least once) historically prevented it from escaping the minus-100-point deficit. Features do not exist in a vacuum, and decisions about features necessaril...
As long as your file names meet operating system requirements, you can use whatever you like; the rest is up to you
A customer had a question about the MSDN documentation on rules for legal file names: My employees keep naming documents with hyphens in the name. For example, they might name a file . It is my position that hyphens should not be used in this way, and the document should be named . Please advise on the use of hyphens within file names. Hyphens inside file names are legal, and you can use as many as you like, subject to the other rules for file names. If you are having an argument with your employees about file naming conventions, that's something you just need to work out among yourselves. Whatever you decid...
Obtaining information about the user's wallpaper on multiple monitors
Today we're going to dump information about the user's wallpaper settings on multiple monitors. The idea is simple. You use the interface on the object to get information about the desktop wallpaper. It will tell you the wallpaper positioning information, whether a single image is being used for all monitors, where those monitors are, and which image is on which monitor. The program proceeds in a few basic steps. We create the object. That object will give us the answers to our questions. Our first question is, "Is the same wallpaper being shown on all monitors?" To determine that, we call and speci...
Why does GetFileVersionInfo map the whole image into memory instead of just parsing out the pieces it needs?
Commenter acq responds (with expletive deleted), "the whole file is mapped into the process' memory only for version info that's certainly only a few kilobytes to be read?" Why not map only the parts that are needed? "I don't understand the necessity to map the whole file except that it was easier to write that code without thinking too much." That was exactly the reason. But not because it was to avoid thinking. It was to make things more secure. Back in the old days, the function did exactly what acq suggested: It parsed the executable file format manually looking for the file version information. (In other ...
Get your hex wrench ready, because here comes the Ikea bicycle
Ikea säljer elcyklar. Click through for two-image slide show. Ikea selling electric bicycles Forget furniture. Ikea is now launching, that's right, an electric bicycle. It goes under the name People-Friendly and costs around 6000 SEK ($900 USD). But only in Älmhult, Småland. People-Friendly has already received three design awards, including the IF Design Award, according to Ikea's press release. What distinguishes it from other electric bicycles is that the battery is hidden in the frame. That makes it look like a regular bicycle as well as lowering the center of gravity and makes t...
It rather involved being on the other side of this airtight hatchway: Denial of service by high CPU usage
You already can do that without doing anything sneaky.
How to take down the entire Internet with this one weird trick, according to Crisis
According to television.
Cargo-cult registry settings and the people who swear by them
Two customers (so far) wanted to know how to increase the duration of taskbar balloon notifications on Windows Vista. (By the way, I gave the answer some time ago.) They claimed that on Windows XP, they were using the registry key , setting the value to a specifying the number of seconds the balloon should appear. They wanted to know if this still worked in Vista. Heck, it didn't work even in Windows XP! That undocumented registry key actually controls whether the Windows XP taskbar should show the "To see the hidden icons, click this button" tip. It has nothing to do with how long the balloo...
Only senior executives can send email to the All Employees distribution list, but mistakes still happen
Some time ago, a senior executive sent email to the All Employees distribution list at Microsoft announcing that a particular product was now available for dogfood. The message included a brief introduction to the product and instructions on how to install it. A few hours later, a second message appeared in reply to the announcement. The second message came from a different senior executive, and it went I got your note and tried it out. Looks good so far. Oopsie. The second senior executive intended to reply just to the first senior executive, but hit the Reply All button by mistake. This would normally have...
Find the index of the smallest element in a JavaScript array
Today's Little Program isn't even a program. It's just a function. The problem statement is as follows: Given a nonempty JavaScript array of numbers, find the index of the smallest value. (If the smallest value appears more than once, then any such index is acceptable.) One solution is simply to do the operation manually, simulating how you would perform the operation with paper and pencil: You start by saying that the first element is the winner, and then you go through the rest of the elements. If the next element is smaller than the one you have, you declare that element the new provisional winner. Ano...
Why is the debugger telling me I crashed because my DLL was unloaded, when I see it loaded right here happily executing code?
A customer was puzzled by what appeared to be contradictory information coming from the debugger. We have Windows Error Reporting failures that tell us that we are executing code in our DLL which has been unloaded. Here's a sample stack: But if we ask the debugger what modules are loaded, our DLL is right there, loaded as happy as can be: In fact, we can view other threads in the process, and they are happily running code in our DLL. What's going on here? All the information you need to solve this problem is given right there in the problem report. You just have to put the pieces together. Let's ta...
Eventually, we may find out where notes eight through twelve came from
CBC Radio's Tom Allen investigates the origin of the opening four notes of the classic Star Trek theme. He traces it to the opening of Mahler's First Symphony, then further back to Brahms's Second Symphony and Beethoven's Fourth Symphony. In college, one of my classmates (the same one that is now the conductor of an orchestra) identified the source of the trumpet fanfare in the Star Trek theme, also known as notes five through seven: Mahler's Seventh Symphony. Skip to timecode 11:05. Eventually, we may find out where notes eight through twelve came from. If the trend keeps up, we may discover that it came fr...
Why does my radio button group selection get reset each time my window regains activation?
A customer reported (all incomplete information and red herrings preserved): We have an issue related to two radio buttons in a window. The code programmatically checks the second button by sending the message. We observe that if the user clicks somewhere else on the screen (so that our application loses focus), and then clicks on the taskbar icon to return to our application, the first radio button spontaneously gets selected. We watched all the messages in Spy++, and it appears that the radio button is receiving a followed by a . Is this by design? If not, what should I be looking for in my code that i...
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?
You start typing.
The code names for various subprojects within Windows 95
Most people know that Windows 95 was code-named Chicago. The subprojects of Windows 95 also had their code names, in part because code names are cool, and in part because these projects were already under way by the time somebody decided to combine them into one giant project. Even when they were separate projects, the first three teams worked closely together, so the names followed a pattern of ferocious cats. My guess is that when the user interface team chose their code name, they heard that the other guys were naming themselves after cats, so they picked a cat, too. I don't know whether they did ...
Creating a simple shell item, just as fake as a simple pidl
Continuing from Creating a simple pidl: For the times you care enough to send the very fake: Instead of creating a simple pidl, we'll create a simple shell item. The idea is the same. We build a file system bind context containing the information about the fake file, and we pass that bind context to the function. Take that program that creates a simple pidl and make these changes: Instead of creating a simple pidl, we create a simple shell item and then extract the same information from it it as before, just doing it the way.
An extensible interlocked arithmetic function (via lambdas)
Some time ago, I noted that you can build other interlocked operations out of . Here's an example: (There's a corresponding C++ version, which I leave as an exercise.) This function atomically updates a "highest value seen so far" variable. It follows the usual pattern: Capture the starting value. Do a computation based on that value. Compare-exchange the new value in. If the compare-exchange failed, then start over. (For bonus points, add an early-out if the operation should be abandoned.) You can make this function extensible by use of lambdas, so that you can update the old value with any computat...
Is WriteProcessMemory atomic?
How could it be?
The mystery of the icon that never appears
A customer reported a problem showing an icon on their dialog box. We verified that this code does execute during the handling of the message. No assertion fires, yet no icon appears either. Our dialog template says The customer did some helpful preliminary troubleshooting: Verify that the code does indeed execute. It sounds obvious, but some people forget to check this. They get distracted trying to figure out why a function isn't working, when in fact the root cause is that you forgot to call the function in the first place. Verify that the call succeeded. That rules out t...
How do I change among the three levels of play in Space Cadet Pinball?
Many many years ago, a customer presumably was taking advantage of the unlimited support part of their support contract when they asked In the documentation for Space Cadet Pinball, it says... The game is divided into three levels of play: basic, intermediate, and advanced. The objective of all levels is to achieve the highest point total. The more advanced the level of play, the greater the point reward. How does one advance to the next level of play? The documentation doesn't explain. The level of play being described in the documentation refers not to any particular in-game option or accomplishment. I...
Enumerating bit sequences with isolated zero-bits via the Fibonacci recurrence
Today's Little Program enumerates bit sequences of a particular length subject to the constraint that you cannot have consecutive 0-bits. This may sound kind of arbitrary, but it is important in magnetic media storage, because you cannot go too long without a flux reversal (traditionally represented by a 1); otherwise, the read head's clock starts to drift and gets out of sync with the data. (The read head uses flux reversals both for signaling and for clock synchronization.) Let's say that an allowable bit sequence is one that contains no consecutive 0-bits. The recurrence for enumerating these types of co...
Even if you're the President, your mother still has the power to embarrass you
Last year, in honor of Mother's Day (the United States version), the John F. Kennedy Library shared a letter sent by President Kennedy to his mother. Mrs. Kennedy had contacted Premier Khrushchev asking for an autographed photo, copies of which were subsequently forwarded to the White House so that the President could sign them as well. President Kennedy tries to express in the politest language he can muster that the mother of a sitting president directly contacting a foreign dignitary is "subject to interpretations", and that in the future, it would be greatly appreciated if she would let the White House clea...
When was the WM_COPYDATA message introduced, and was it ported downlevel?
Gabe wondered when the message was introduced. The message was introduced by Win32. It did not exist in 16-bit Windows. But it was there all along. The The message was carefully designed so that it worked in 16-bit Windows automatically. In other words, you retained your source code compatibility between 16-bit and 32-bit Windows without having to do a single thing. Phew, one fewer breaking change between 16-bit and 32-bit Windows. As Neil noted, there's nothing stopping you from sending message in 16-bit Windows with a window handle in the and a pointer to a in the . Since all 16-bit applications ra...
How can you use both versions 5 and 6 of the common controls within the same module?
Commenter Medinoc was baffled by the statement that the decision to use the visual-styles-enabled version of the common controls library is done on a window-by-window basis. " Isn't it rather on a per-module basis, depending on each module's manifest? If it is indeed on a per-window basis, how does one choose?" Whether a particular call to (or one of its moral equivalents) gets the classic version of the control or the visual-styles-enabled version of the control depends on which activation context is active at the point of the call. If an activation context with version 6 of the common controls is active, th...
Why does saving a file in Notepad fire multiple FindFirstChangeNotification events?
Many people have noticed that the and functions (and therefore their BCL equivalent and WinRT equivalent ) fire multiple events when you save a file in Notepad. Why is that? Because multiple things were modified. Notepad opens the file for writing, writes the new data, calls to truncate any excess data (in case the new file is shorter than the old file), then closes the handle. Two things definitely changed, and a third thing might have changed. It's therefore not surprising that you got two events, possibly three. Remember the original design goals of the function: It's for letting an application ca...
Letting the boss think your project is classier than it really is
Once upon a time, there was a team developing two versions of a product, the first a short-term project to ship soon, and the other a more ambitious project to ship later. (Sound familiar?) They chose to assign the projects code names Ren and Stimpy, in honor of the lead characters from the eponymous cartoon series. Over time, the two projects merged, and the code name that stuck was Ren. When the project came up in a meeting with Bill Gates, it was mentioned verbally but never spelled out, and since Bill wasn't closely tuned into popular culture, he mapped the sound /rɛn/ not to the hairless Mexican dog...
Warehouse holding 1000 cans of surströmming burns to the ground, insert punch line here
A warehouse in Sweden holding 1000 cans of surströmming burned to the ground last week. No people were injured. The cans of surströmming, already prone to violent decompression under normal conditions, exploded over a period of six hours. Some of them turned into projectiles and shot through the air. No information on what effect this will have on the supply of surströmming ice cream. I knew you were wondering.
Getting the location of the Close button in the title bar
Today's Little Program locates the × button in the corner of the window and, just to show that it found it, displays a balloon tip pointing at it. Let's start with the program from last week, the one that displays a balloon tip, then make these changes: Instead of positioning the balloon at the cursor position, we put it at the center of the Close button. We use the message to obtain information about the window title bar, specifically checking information about the Close button. After verifying that it is visible and on-screen and enabled, we calculate its center point and return success. The me...
If a lot of settings are ignored when set in a DLL, why bother even letting you set them on a DLL?
There are many settings that are ignored when set in a DLL. . and . There are plenty of others. Commenter 640k asks why these settings even exist for DLLs if they has no effect. Because they are settings for PE modules in general. If there were separate file formats for EXEs and DLLs, then there would have to be two different module loaders, one for EXEs and one for DLLs. This creates extra work for no particular benefit aside from satisfying some anal-retentive compulsion that nothing be wasted. As far as I can tell, all operating systems use a common file format for both executables and libraries. If it...
How do I extract an icon at a nonstandard size if IExtractIcon::Extract tells me to go jump in a lake?
Commenter Ivo notes that if you ask to extract an icon at a particular size, the function can return which means "Go jump in a lake do it yourself." But how can you do it yourself? The and functions don't let you specify a custom size, and doesn't work with icon indices (only resource IDs). The function comes to the rescue. This takes all the parameters of (plus a bonus flags parameter), and it will actually do an extraction. Let's extract an icon from Explorer at 48×48, just for illustration. As usual, start with our scratch program, then make these changes: Run the program, and observe th...
The StartRunNoHOMEPATH policy affects whether the user's HOME path is the current directory when you use Start.Run, but make sure you read that carefully
A customer (via the customer liaison) discovered that even though they had set the policy, they found "if the user creates a Notepad file, the file is searched in the user's HOME directory, in contradiction of policy," I asked the liaison to confirm: "The steps you describe are rather vague. Are you saying that the problem occurs when the user opens the Run dialog and types ?" The customer liaison replied, "I believe the scenario is close to what you describe. The user opens the Run dialog, types , then types some text into Notepad and then does a Save As. I will confirm with the customer." A few days later...
Why does the common file save dialog create a temporary file and then delete it?
When you call , the common file save dialog will ask the user to choose a file name, and just before it returns it does a little create/delete dance where it creates the file the user entered, and then deletes it. What's up with that? This is a leftover from the ancient days of 16-bit Windows 3.1, back when file systems were real file systems and didn't have this namby-pamby "long file name" or "security" nonsense. (Insert sound effect of muscle flexing and gutteral grunting.) Back in those days, the file system interface was MS-DOS, and MS-DOS didn't have a way to query security attributes because, well, ...
Showing a balloon tip at a specific position, then removing it
Today's Little Program shows a balloon tip at a specific position, then manually removes it. Start with our scratch program and make these changes: When our main window is created, we also create a balloon-style tooltip and add a tracking tool. Normally, the tooltip control appears and disappears automatically, at a position of the tooltip's choosing. Tracking tooltips are managed manually, so you can specify exactly when and where they appear, and you also manually remove them from the screen. At startup, we add the tool but do not show the balloon tooltip yet. When the user presses the space bar, we get...
A discovered quirk is just few steps away from becoming a feature
Commenter Cherry wonders who invented all those strange syntaxes, like to show all environment variables, including the hidden ones. An interesting historical note is the origin of the convention in unix that files whose names begin with a dot are hidden by default (here's the relevant portion). That article highlights how a discovered quirk is just a few steps away from becoming a feature. As Master Yoda might put it: Discovery leads to dissemination. Dissemination leads to adoption. Adoption leads to entrenchment. Entrenchment creates a compatibility constraint. As I've noted many times, the batch la...
I thought you could use SWP_FRAMECHANGED to force a control to recalculate its properties after a change in styles
Simon Cooke dug back into his memory and asked, "Doesn't calling with cause a recreate and re-apply of the styles?" The flag does not recreate anything, but it does reapply the styles, as far as it knows. Recall that the bits in the window style break into two parts. There are the styles managed by the window manager, which are in the upper 16 bits, and there are the styles that are specific to each control, which are in the lower 16 bits. The window manager knows about the styles that it manages, but it has no clue about the styles that are specific to each control. It has no idea that the style control...
How do I programmatically create folders like My Pictures if they were manually deleted?
A corporate customer had a problem with their employees accidentally deleting folders like Videos and Pictures and are looking for a way to restore them, short of blowing away the entire user profile and starting over. They found some techniques on the Internet but they don't always work consistently or completely. What is the recommended way of recreating these missing folders? It turns out that the customer was asking a question that I answered many years ago, but looking at it from the other side. To recreate a folder, call with the flag , or call and pass . If you are targeting Windows Vista or higher,...
Le Chatelier's Principle in action: Administrative overrides
Today we have another example of Le Chatelier's Principle as interpreted by John Gall: Every system resists its proper functioning. There was a video card manufacturer which was using the key so that they could inject their DLL into every process. I have no idea why. Perhaps to get a nice bonus. In Windows Vista, the registry key was deactivated for both engineering and security reasons. Oh no! Undeterred, the video card manufacturer issued an update to their driver so that in addition to adding themselves to , they also set the administrative override switch that re-enabled the feature. Boom, they probab...
How can I get information about the items in the Recycle Bin from script?
Today we'll do a scripting version of an old C++ program: Printing information about the items in the Recycle Bin. (How you wish to act on the information is up to you.) This is a pattern we've seen a lot. Bind to a folder, enumerate its contents, extract properties. Wow, that was way easier than doing it in C++! Just for fun, I'll do it in C#, first as a straight port: We have to cast to because the default interface for the method is , but is a method on . We didn't have to do this explicit cast in JavaScript because JavaScript is a dynamically-typed language. So let's use the keyword to mimi...
Raymond's house rules for Easter Egg Hunts
One of my colleagues frustrates his family by hiding the eggs for the annual Egg Hunt way too well. "Apparently, drawers and freezers are out of bounds in the traditional egg hunt." Here are my house rules for Easter Egg Hunts: Personally, I like to hide eggs in plain sight. It's surprising how long it can take somebody to find a yellow egg resting brazenly on the lap of a yellow teddy bear.
How do I set a breakpoint on a function whose name contains spaces or other special characters?
If you use one of the command line debuggers based on the Debugger Engine, you can set a breakpoint on a function whose name contains spaces or other special characters by quoting the symbol name. The trick here is that you do not quote the entire string; you quote only the symbol name. Note that the quotation marks do not go around the part. They go only around the symbol. (Otherwise, the debugger thinks you are setting a breakpoint action.) Another trick for setting breakpoints is using tab autocompletion for symbols. If you type and then hit Tab repeatedly, you will cycle through all the matches. (It ...
How can I get the Windows 8 touch keyboard to display autocomplete suggestions like the Bing app?
A customer observed that if you use the Windows 8 Bing app with the touch keyboard, the top of the touch keyboard includes autocomplete suggestions for quick access. They wanted to know how to enable this in their own application. In the illustration below, it's the two boxes immediately above the keyboard with the words "aol" and "amazon". The ones that slide into view. | a| SUGGESTIONS aol amazon att.net autotrader ask.com american airlines aol amazon q w e r t y u i o p 	...
There is no complete list of all notifications balloon tips in Windows
A customer wanted a complete list of all notifications balloon tips in Windows. There is no such list. Each component is responsible for its own balloon tips and is not required to submit their list of balloon tips to any central authority for cataloging. In order to create such a list, somebody would have to go contact every component team and ask them for a list of all their balloon tips, and that component team would probably undertake a search of their code base looking for balloon tips. And figuring out the text of each balloon tip can be tricky since the text may be built dynamically. (And the customer did...
The gradual erosion of the car trip experience, part 2
When I learned that my nieces were heading out on a road trip, I asked, "Are you going to sing songs?" My eldest niece looked at me as if I were from Mars, then replied, "No, we bring electronics."
Microspeak: bar check
A bar check sounds like the sort of thing you receive at the end of a long evening of drinking, but that's not what a bar check is. Among the things that happen at ship room meetings is reviewing each bug that has a proposed fix and deciding whether to accept or reject the fix. Another thing that happens at ship room meetings is the bar check: The person representing the bug describes the issue and what is known about it so far and asks for a preliminary assessment from the ship room as to whether this is the sort of bug they would approve if a fix were available, in other words, whether it meets the bug bar....
The geeky thrill of discovering that two things are really the same thing, just with different labels
Today's post about binomial coefficients was intended to be a warm-up for Catalan numbers, but it turns out Eric Lippert already covered them, first in the context of binary trees, then in the context of arbitrary trees and forests, and then again in the context of matched parentheses. Another way of seeing the correspondence between forests and matched parentheses is simply to consider each as an XML open-tag and each as an XML end-tag. One thing to take away from the enumeration of objects controlled by Catalan numbers is that when you see multiplication in a recurrence relation, that typically correspo...
Enumerating subsets with binomial coefficients
Inspired by the Little Program which enumerates set partitions, I decided to do the binomial coefficients this week. In other words, today's Little Program generates all subsets of size k from a set of size n. As before, the key is to interpret a recurrence combinatorially. In general, when a recurrence is of the form A + B, it means that at the recursive step, you should do A, followed by B. In our case, the recurrence is C(n, k) = C(n − 1, k) + C(n − 1, k − 1). The combinatorial interpretation of the recurrence is to look at how you can go from a set of size n to a set of size n − 1 ...
Windows is not a Microsoft Visual C/C++ Run-Time delivery channel
There's a DLL in the system directory called , and from its name, you might think that it is the Microsoft Visual C/C++ Run-Time library. That is a perfectly reasonable guess. But it would also be wrong. The Microsoft Visual C/C++ Run-Time libraries go by names like or or or , and the debugging versions have a in there, too. And like MFC, these binaries might be on your machine as a side effect of the implementation of a particular Windows component, but they are not contractual. If your program requires the Visual C/C++ Run-Time library, then your program needs to install the appropriate version. (Ther...
Why does PrintWindow hate CS_PARENTDC? redux
Why does hate ? Because everybody hates ! Commenter kero claims that it's "easy to fix" the problem with and . You just remove the style temporarily, then do the normal , then restore the style. The question is then why simply doesn't do this. The question assumes that the described workaround actually works. It may work in limited situations, but it certainly doesn't work in general. Since the style is a class style, removing the style affects all windows of that class, not merely the window you are trying to print. Suppose there are two windows of the class running on different threads, and you remov...
What happens to my COM server-side object when clients die unexpectedly?
They get cleaned up eventually.
Why is Rundll32 called Rundll32 and not just Rundll?
There is an oft-abused program named . Why does its name end in ? Why not just call it ? (I will for the moment ignore the rude behavior of calling people stupid under the guise of asking a question.) Because there needed to be a way to distinguish the 16-bit version from the 32-bit version. Windows 95 had both (the 16-bit version) and (the 32-bit version). Of course, with the gradual death of support for 16-bit Windows, the 16-bit is now just a footnote in history, leaving just the 32-bit version. But why did the two have to have different names? Why not just use the same name () for both, putting t...
Using WM_SETREDRAW to speed up adding a lot of elements to a control
Today's Little Program shows one way you can implement a better version of . Our first version doesn't use at all. Start with the scratch program and make the following changes: Most of this program was stolen from my scroll bar series. The interesting new bits are that you can add one new item by hitting 1, or you can add ten thousand items by hitting 2, or you can add ten thousand items with redraw disabled by hitting 3. I drew the items in reverse order so that adding an item forces everything to change position, so that the effect of the redraw is more noticeable. Observe that adding one item is f...
It's bad enough for a guest to demolish the host's house; demolishing an unrelated person's house is taking it to a whole new level
"How do I destroy a window that belongs to another process?" The function will not destroy windows that belong to another thread, much less another process. The best you can do is post a message to the window to ask it nicely. The function response to the message by destroying the window, but the window is free to add a custom handler for the message which rejects the request. (If you are thinking of posting the message, then you're the sort of person who prank-calls somebody pretending to be the police.) If you want to distinguish between user-initiated requests to close the window (say, by clickin...
Why does the access violation error message put the operation in quotation marks? Is is some sort of euphemism?
When an application crashes with an access violation, the error message says something like The instruction at "XX" referenced memory at "YY". The memory could not be "read". Why is the operation in quotation marks? Is this some sort of euphemism? The odd phrasing is a consequence of globalization. The operation name is a verb in the infinitive ("read", "write"), but depending on how the containing message is localized, it may need to take a different form. Since the kernel doesn't understand grammar, it just puts the words in quotation marks to avoid having to learn every language on the planet. Imagine if i...
It rather involved being on the other side of this airtight hatchway: Invalid parameters from one security level crashing code at the same security level (again)
A few years after I posted this story, the security team received something very similar. If have found that if you call the XYZ function (whose last parameter is supposed to be a pointer to a ) and instead of passing a value pointer to a , you pass , then you can trigger an access violation in the XYZ function. The XYZ function does not check whether the input parameter is . This is a denial of service attack against the system. Okay, first of all, even if the XYZ function checked that the final parameter is non-, that wouldn't prevent a caller from passing an invalid non- pointer, so adding a check doesn...
Buggy milk cartons, beeping computers, and other silliness
Some time ago, there was a performance-related bug that went something like this: mm/dd/yy Created by bob The attached file contains a dataset that takes a very long time to process. The engineer who fixed the problem decided to take the cryptic approach: mm/dd/yy Resolved as fixed by alice It got better. It was a common practice during highly stressful periods to file humorous bugs in the defect tracking system, and once the initial bug was filed, it turned into a sort of collaborative performance effort. For some reason, milk is often a trigger. Many years ago, the vendor who supplies milk to Microsof...
A puzzle involving dynamic programming, or maybe it doesn't
Here's a programming challenge: Evaluate the following recurrence relation efficiently for a given array [x0, …, xn−1] and integer k. Hint: Use dynamic programming. In words: If the array has only two elements, then the result is the average of the two elements. If the array has more than two elements, then then the result is the sum of the following: Half the value of the function evaluated on the array with the first element deleted and the second parameter incremented by one. Half the value of the function evaluated on the array with the l...
The dangers of buffering up posted messages and then reposting them later
A customer wanted to check that their idea for solving a re-entrancy problem doesn't have any hidden gotchas. We have a window which processes incoming work. One of our work items enters a modal loop, and if new work gets posted to the window while the modal loop is running, our work manager gets re-entered, and Bad Things happen. Our proposed solution is to alter the modal loop so that it buffers up all messages destined for the worker window. (Messages for any other window are dispatched normally.) When the modal loop completes, we re-post all the messages from the buffer, thereby allowing the worker wind...
Functions that return GDI regions rarely actually return regions
For reasons I don't quite understand, the only functions in GDI and USER which create GDI regions are the functions with in their name, like or . All the other functions which return a region require you to pass an existing region to use as the output. I can see this being useful for , because you can set your output region to be equal to one of the input regions in order to update a region in place. But for all of the functions, having to create an output region is usually just an annoyance. I guess it lets you reuse a single dummy region over and over again, but in practice, you're just going to des...
Can CoCreateGuid ever return GUID_NULL?
A customer asked whether the function can ever return . Their code uses for special purposes, and it would be bad if that was ever returned as the GUID for an object. "Can we assume that never returns ? Or should we test the return value against , and if it is equal, then call and try again?" Some people started running a bunch of times and observing that it was spitting out type 4 GUIDs, which will always have a 4 in the version field. Then other people started wondering whether the use of Algorithm 4 was contractual (it isn't). Then still other people went back to read the RFCs which cover UUIDs...
Geeky t-shirt alert: Windows 7's so-called God Mode
Back in 2010, the so-called God Mode was the hit discovery of the Internet, at least until the next cute cat video made the rounds. If you had stopped by the Microsoft Visitor Center during that meme's brief moment in the sun, and wandered into the gift shop, you could have picked up a t-shirt that said on the front. Of course, if you actually wore that shirt, you would also get stuffed into a locker and have your lunch money stolen from you.
Enumerating set partitions with Bell numbers and Stirling numbers of the second kind
Just for fun, today's Little Program is going to generate set partitions. (Why? Because back in 2005, somebody asked about it on an informal mailing list, suggesting it would be an interesting puzzle, and now I finally got around to solving it.) The person who asked the question said, Below we show the partitions of [4]. The periods separate the individual sets so that, for example, 1.23.4 is the partition {{1},{2,3},{4}}. I replied with a hint, saying, "This page explains what you need to do, once you reinterpret the Stirling recurrence as an enumeration." Only now, writing up this post, did I real...
Different senses of scale create different travel expectations
A friend of mine had a business meeting near London, and he decided to extend it to a tour of Scotland and England once the meetings were over. (This is the same friend who took me on the emergency vacation many years ago.) His plan was to rent a car early one morning and drive from the meeting location all the way up to Aberdeen at one go, then slowly work his way back south, enjoying the sights along the way. He sanity-checked his plan against his colleagues from Great Britain. "I looked it up on multiple online mapping sites, and they all say that the trip from London to Aberdeen is doable in a day. I take m...
Why can’t I __declspec(dllexport) a function from a static library?
You can, but the function needs to be linked in.
When visitors to the United States underestimate the size of the country
A friend of mine who is from Lebanon (but now lives in Seattle) invited his grandmother to come visit for the summer. When she arrived, he asked her, "Grandma, is there anywhere in particular you would like to visit?" His grandmother replied, "I'd like go to to Washington, DC." "Okay, Grandma. Let me buy some plane tickets." "No, let's drive." "You want to drive all the way to Washington, DC? Here, let me show you on a map how far away it is." Grandma replied, "Let's do it." My friend said, "Okay, Grandma, we're going on a road trip!" He got the rest of the family on board with the plan, packed up the car, ...
Going for the facts: Who is displaying this message box?
A customer wanted to know whether had a problem with Unicode. A problem with it? Quite the contrary. loves Unicode! In fact, if you call the ANSI version, it converts the strings to Unicode and then finishes the work in Unicode. Okay, here's the customer's problem. We have a custom application written in managed code. When we launch the process from unmanaged code via , we sometimes get a bogus error message: WARNING! The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. The filena...
I think this person's monitor is broken: It doesn't know how to render text in capital letters
Some time ago, somebody asked a question about why, when they do 1 and 2, they get extra thing 3. "The extra 3 is there because of the 456 feature. BUT DO NOT DISABLE THE 456 FEATURE JUST BECAUSE YOU DON'T LIKE 3. The 456 feature is important, because it ensures that 2 runs to completion. Otherwise, you risk data loss." The person wrote back, "I disabled the 456 feature, and that fixed it. Thanks!" It appears that that person's monitor is broken: It doesn't know how to render text in capital letters.
Raymond's highly scientific predictions for the 2014 NCAA men's basketball tournament
Once again, it's time for Raymond to come up with an absurd, arbitrary criterion for filling out his NCAA bracket. This year, I look at the number of followers of of the basketball team's official Twitter account, or one tenth of the number of followers of the school's athletic department if the school's basketball team does not have its own dedicated Twitter account. The fraction 1/10 is completely arbitrary, but that's what makes this algorithm highly scientific. And yes, counting fans also includes people who hatewatch the team. I accept this, because if a lot of people hate a team, it's probably because...
Why do I have to hit an arrow key before a keyboard-initiated Move operation will follow the mouse?
TehShrike wonders why you have to hit an arrow key before a keyboard-initiated Move operation will follow the mouse. I don't know, but I think it's just a bug. Mind you, it's a bug with extraordinary seniority (probably going as far back as Windows 1.0). The Move and Size commands from the system menu are operated by the same common function, and the keyboard-initiated Size command requires you to hit an arrow in order to specify which edge you are trying to resize. The Move command doesn't need to let you pick a side (since moving is independent of sides), but the common helper function waits for the arr...
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?
A customer was writing a program in (and this is what they said) "32 bit C++ .Net 4.0" which displayed the contents of a directory, and they wanted to filter out items such as hidden files and protected operating system files (also known as super-hidden files) based on the user's current Explorer preferences. Furthermore, they wanted to show localized folder names, such as Usarios instead of Users, again, the same way Explorer does. They are currently using . The way to do this is to use , the same way Explorer does. Don't pass or , and you will get the default enumeration that filters out hidden items based ...
How do I create an IShellItemArray from a bunch of file paths?
The interface accepts bulk operations in the form of an . So how do you take a list of file names and convert them into an ? There is no function, but there is a , and we know how to convert a path to an ID list, namely via . So lets snap two blocks together. The template function takes an array of paths and starts by creating a corresponding array of ID lists. (If you're feeling fancy, you can use a file system bind context to make simple ID lists.) It then pumps this array into the function to get the item array. Using a template allows you to pass an array of anything as the array of paths, as lo...
Why does the Directory.GetFiles method sometimes ignore *.html files when I ask for *.htm?
The documentation for the method says When using the asterisk wildcard character in a searchPattern, such as "*.txt", the matching behavior when the extension is exactly three characters long is different than when the extension is more or less than three characters long. A searchPattern with a file extension of exactly three characters returns files having an extension of three or more characters, where the first three characters match the file extension specified in the searchPattern. A searchPattern with a file extension of one, two, or more than three characters returns only files havin...
Operations jargon: Internet egress
As I've noted before, the operations team has their own jargon which superficially resembles English. Some time ago, they sent out a message with the subject A New Internet Egress Path Is Coming. Translation: We're changing the way computers access the Internet. Bonus jargon: traffic on the edge. This does not refer to traffic that is on the verge of a nervous breakdown. It merely refers to traffic that crosses the boundary between intranet and Internet.
On live performances of Star Trek
Spock's Brain is generally considered to be the worst episode of Star Trek. That may be why in 2009 Mike Carano decided to perform it as a theatrical production. Here is the opening scene, and here's Carano talking about the show's genesis. In the second video, skip ahead to 2:40 to see more clips from the show, or go to 4:35 for the fight scene. Whereas Carano played the show for laughs, the folks at Atomic Arts in Portland (yes, that Portland) played it straight for their Trek in the Park series, but they still get laughs because Star Trek. And yes, when the Enterprise is hit, everybody jerks to the lef...
How do I disable zone markers for downloaded files, so that Explorer stops being a nag about running downloaded files and just trusts me to do the right thing?
My Little Program about manipulating the zone identifier for downloaded files appears to have struck a nerve with commenter Tess, who launched into some sort of diatribe about how Microsoft should stop being a busybody and warning users about opening files that they downloaded. You are welcome to disable the feature if it offends you so. In the Group Policy editor, go to User Configuration, Administrative Templates, Windows Components, Attachment Manager, and enable Do not preserve zone information in file attachments. For bonus points, you can set a bunch of other policies to make your computer even more dan...
Why Johnny can't read music
In the book He Bear, She Bear, the musical instrument identified as a tuba is clearly a sousaphone. (For those who are wondering what the title has to do with the topic of musical instrument identification: It's a reference to the classic book Why Johnny Can't Read.)
Programmatically uploading a file to an FTP site
Today's Little Program uploads a file to an FTP site in binary mode with the assistance of the Wininet library. This program has sat in my bag of tools for years. The program accepts five command line arguments: site (no "ftp://" in front) userid password path for the file to upload location to place the uploaded file For example, I might say ftpput ftp.contoso.com admin seinfeld newversion.zip subdir/newversion.zip
Converting from a UTC-based SYSTEMTIME directly to a local-time-based SYSTEMTIME
Last year, I presented this commutative diagram A 2-by-2 grid of boxes. The top row is labeled FILETIME; the bottom row is labeled SYSTEMTIME. The first column is labeled UTC; the second column is labeled Local. The upper left box is labeled GetSystemTimeAsFileTime. There is an outgoing arrow to the right labeled FileTimeToLocalFileTime leading to the box in the second column labeled None. There is an outgoing arrow downward labeled FileTimeToSystemTime leading to the box in the second row, first column, ...
We’re currently using FILE_FLAG_NO_BUFFERING and FILE_FLAG_WRITE_THROUGH, but we would like our WriteFile to go even faster
Actually, those flags make it go slower.
Why do I have to add 1 to the color index when I set it as the hbrBackground of a window class?
Our scratch program sets the background color to by setting the class background brush as follows: What's with the ? Okay, first of all, let's backtrack a bit. The real first question is, "What's the deal with taking an integer () and casting it to a and expecting anything sane to happen?" The window manager wants to provide multiple ways of setting the class background brush. The application can request that no automatic background drawing should occur at all. The application can request custom background drawing and provide that custom drawing by handling the message. The application...
What order does the DIR command arrange files if no sort order is specified?
Whatever order it likes.
What two-year-olds think about when they are placed in time-out
My niece (two years old at the time) was put in the corner as punishment for some sort of misdeed. At the expiration of her punishment, her grandfather returned and asked her, "你乖唔乖?" (Are you going to be nice?) She cheerfully replied, "仲未乖!" (Still naughty!) In an unrelated incident, one of my honorary nieces was being similarly punished. She told her aunt who was passing nearby, "In a little while, my daddy is going to ask me if I'm sorry. I'm not really sorry, but I'm going to say that I am."
Adventures in automation: Dismissing all message boxes from a particular application but only if they say that the operation succeeded
Suppose you have a program that is part of your workflow, and it has the annoying habit of showing a message box when it is finished. You want to automate this workflow, and part of that automation is dismissing the message box. Let's start by writing the annoying program: This annoying program pretends to do work for a little while, and then displays a message box saying whether or not it succeeded. (Let's say it succeeds 80% of the time.) Our Little Program will automate this task and respond based on whether the operation succeeded. This is just a small extension of our previous program which logs the...
How can I detect that my program was run from Task Scheduler, or my custom shortcut, or a service, or whatever
Suppose you want your program to behave differently depending on whether it is launched from the Start menu, or by clicking the pinned icon on the taskbar, or by Scheduled Task, or from a service, or whatever. How can a program detect and distinguish these scenarios? The answer is you don't. And you shouldn't try. Instead of trying to guess how your program was executed, you should have the launcher tell you how they are executing your program. You do this by registering a different command line for each of the scenarios, and then checking for that command line in the program. (We saw a variation of this a lit...
What does the SEE_MASK_UNICODE flag in ShellExecuteEx actually do?
Somebody with a rude name wonders what the flag does. It does nothing. The flag was introduced when porting the Windows 95 shell to Windows NT. It happened further back in history than I have permission to access the Windows source code history database, but I can guess how it got introduced. One of the things that the porting team had to do was make Unicode versions of all the ANSI functions that Windows 95 created. Sometimes this was done by creating separate A and W versions of a function. Sometimes this was done by having separate A and W versions of an interface. Sometimes by adding a...
Why are leading digits converted to language-specific digit shapes, but not trailing digits, and how do I suppress the conversion entirely?
If you have a string like , and you render it on an Arabic system, you might get ٠١٢٣٤ABCDE67890. The leading digits are rendered as Arabic-Indic digits, but the trailing digits are rendered as European digits. What's going on here? This is a feature known as contextual digit substitution. You can specify whether European digits are replaced with native equivalents by going to the Region control panel (formerly known as Regional and Language Options), clicking on the Formats tab, going to Additional settings (formerly known as Customize this format), and looking at the options under...
A simple email introduction: Fan mail
One of my former colleagues on the Windows kernel team wasn't afraid to make changes all across the system when necessary. If the engineering team decided to upgrade to a new version of the C++ compiler, my colleague was the one who gave it a test-drive on the entire Windows source code, and fixed all the warnings and errors that kick up as well as ensuring that it passed the build verification tests before updating the compiler in the official toolset. Beyond that, my colleague also ran around being a superhero, writing tools that needed to be written, fixing tools that were broken, and generally being somebo...
Nieces sometimes extrapolate from insufficient contextual data
My brother-in-law enjoys greeting his nieces when they come over to visit by throwing them into the air and asking, "叫聲我?" (Who am I?) The nieces happily reply, "舅舅." (Uncle.) He then tosses them up into the air a second time and says, "大聲啲!" (Louder!) And the nieces happily shout, "舅舅!" One time, my wife was talking with her brother at a normal volume, and his niece came into the room and said to my wife, "大聲啲! 舅舅聽唔到!" (Louder! Uncle can't hear you!) Update: Per Frank's suggestion b...
Logging the contents of every message box dialog via automation
Today's Little Program logs the contents of every message box dialog, or anything that vaguely resembles a message box dialog. (Since there's no way for sure to know whether a dialog box is a message box or not.) This is the same pattern as the program we wrote last week, but with different guts when the window opens. This time, we see if the class name is , which UI Spy tells us is the class name for dialog boxes. (That this is the numerical value of is no coincidence.) If we have a dialog, then we look for a child element whose automation ID is , which UI Spy tells us is the automation ID for the text ...
How can I make sure my program is launched only from my helper program and no other parent?
Say you have a collection of programs which work together. One of them is the "master" program that runs the show, and it has a bunch of "assistant" programs that it launches to accomplish various subtasks. These assistants are not meant to be run by themselves; they are meant to be run only by the master program. How do you design the assistant so that it can only be run by the master? There's nothing you can do to force the assistant to be run only by the master, since anything you do to detect the case can be faked out by an attacker. (Worst case is that they just run your program under the debugger and patch...
What is the programmatic equivalent to unchecking the box to prevent a file from having its contents indexed?
A customer wanted to know how they could write a program that automatically checked and unchecked the box that appears on a file's property sheet on the General tab, clicking the Advanced button, and then checking or unchecking the item whose name keeps changing: The checkbox maps to the file attribute formally known as , and informally known as (pronounced like the word fancy). Checking the box clears the attribute, and unchecking the box sets the attribute. The customer liaison replied, "Thanks for your assistance. The customer was able to use the method with the values in the enumeration to manipulate t...
When will the static control automatically delete the image loaded into it, and when is it the responsibility of the application?
If you create a static control with initial contents (for example, by creating a or control in a dialog template), then the static control will load the contents upon creation and destroy the contents upon destruction. So at least in the case where you don't touch the static control, things will work automatically. But once you touch it, things get confusing. If you send the message to a static control, this does a few things (assuming your parameters are all valid): The previous image is replaced by the new image you passed. The message returns a handle to the previous image. The static control turns o...
If you cancel an operation while it's in progress, then it's not surprising that it's only half-done
A customer (via their customer liaison) started by asking why they were seeing an unexpected access control entry in the security descriptor of an object. The ACEs on the parent grant access to Administrators, CREATOR OWNER, SYSTEM, and Users, but the ACEs on the child object (which should simply have been inherited from the parent) include an extra entry for Bob. How did Bob get access to the child object? When we view the details of the ACEs, it lists the Bob entry as Inherited from parent. But there is no Bob entry in the parent! I observed, "Probably because Bob is the CREATOR OWNER." Thanks for the expla...
The Grand Duke's monocle is an affectation
In the Disney adaptation of Cinderella, the Grand Duke wears a monocle. The monocle moves from eye to eye during the course of the story. The Grand Duke's monocle is an affectation. Either that, or he needs a full pair of glasses, but is very frugal.
Writing automation to wait for a window to be created (and dismiss it)
Today's Little Program uses UI Automation to cancel the Run dialog whenever it appears. Why? Well, it's not really useful in and of itself, but it at least provides an example of using UI Automation to wait for an event to occur and then respond to it. Okay, let's see what's going on here. The program registers a delegate with UI automation which is called for any event that is an immediate child () of the root (). This will catch changes to top-level unowned windows, but not bother firing for changes that occur inside top-level windows or for owned windows. Inside our handler, we check if the window's t...
When someone proposes marriage, bear in mind that there is a question that needs to be answered
A colleague of mine was at a restaurant, and he spotted a young couple at the next table. The woman fawned over a classic diamond engagement ring, and when she put it on her finger, he decided that it was safe to ask them about it. They had gotten engaged earlier that day, and the man told the story of the proposal, up to the point where he asked her to marry him. My colleague then turned to the woman and teasingly asked, "And what did you say?" The woman chuckled, then suddenly her eyes opened wide with the realization that she had skipped over this important technical detail. She became dead serious and very...
Debugging: Diagnosing why malloc is failing
A customer had some code which was experiencing memory allocation failures when calling (which maps to ). The function returns , and reports . However, there was still plenty of memory free: The customer was continuing their investigation but was looking for some pointers since the bug took a day to emerge. Could it be heap fragmentation? (The program is uses the regular C runtime heap and does not enable the low-fragmentation heap.) One of the suggestions was to run the VMMap utility to see if the problem was exhaustion of virtual address space. And lo and behold, that was indeed the cause. The code had ...
When something gets added to a queue, it takes time for it to come out the front of the queue
SendInput puts it at the end.
The heavy metal umlaut encroaches into Seattle real estate
The heavy metal umlaut is creeping into Seattle real estate. I submit for your consideration the condominium known as Bleü. I can't even tell what language they are trying to pretend to be. There are other properties in Seattle with dots, but at least the dots aren't gratuitous. Hotel Ändra in Belltown takes its name from the Swedish word meaning to change. (The hotel is consistent with its use of the dots, but outsiders frequently omit them, changing the hotel's name to Andra, which means "Others".) Hjärta Condos takes its name from the Swedish word meaning heart. Hjärta is in the Ballar...
What is this extra thread in my process?
A customer liaison asked: After applying Service Pack 2 to Windows Server 2003, my customer found that a simple MFC application (just using the template, no customization) has two threads when it is supposed to have only one. After five minutes, one of the threads exits. This doesn't happen on Windows Server 2003 RTM or Windows Server 2003 Service Pack 1. Here is a stack trace of the extra thread: The parameters to seem to be consistent with . Assuming that's the case, the parameters are Can you explain what the purpose of this thread is? Did this behavior change as a result of the update? ...
Microspeak: Party, in various forms
To use with abandon.
Excuses I learned from babies
I was visiting a friend of mine, and his young daughter was being unusually cranky. He explained, "Oh, she's teething." I filed that away as an excuse I could use the next time I felt cranky. "Sorry about that. I'm teething." Here's another excuse you might want to use: "No, I'm not drunk. I simply lost interest in remaining upright."
Execute a file as if it were a program, even though its extension is not EXE
Today's Little Program executes a file as if it were a program, even though its extension is not EXE. The idea here is to prevent somebody from running your program by accident, so you give it an extension like . This is great for preventing somebody from running the program by mistake, but how do you do it on purpose? We're merely using the member of the structure to force the file to be interpreted as the type we specify, overriding the default type inference code.
VirtualLock locks your memory into the working set, even if your threads are blocked
Today, a correction to an earlier article on . When you lock memory with , it will remain locked even if all your threads are blocked. As noted in the Follow-up section at the end of the referenced article, the behavior of the operating system never changed. Virtually-locked pages were never unlocked in practice. What changed is that an implementation detail was elevated to contract. The intention when was originally designed was that virtually-locked pages were potentially unlockable if the application is not running. However, the memory manager folks never got around to implementing that part. At some point,...
The United States Team uniforms for the opening ceremony is rather hideous, and illegal, and a bit anachronistic
By the time you read this, the opening ceremony for a large sporting event organized by a lawsuit-happy organization may already have taken place. As part of the ceremony, the team representing the United States entered wearing ugly uniforms. They're so ugly that even the hideous Christmas sweater in your closet, the one with the reindeer and wreaths and candy canes, actually steps out, points, and laughs, saying "Ha ha, what an ugly sweater!" If you study the picture carefully, you will observe a number of things. First of all, the incorporation of the flag into the sweater pattern (and once in the pants) v...
If an asynchronous I/O completes synchronously, is the hEvent in the OVERLAPPED structure signaled anyway?
Yes. When an I/O completes (whether synchronously or asynchronously), the event is signaled and completion status notifications are queued. The function can be used to wait on an I/O that has already completed; it will merely return immediately. If you ask whether the I/O has completed, and the I/O completed synchronously, it will correctly report, "Yeah, of course it completed. Heck, it completed a long time ago!" In other words, you can logically treat the case of an asynchronous I/O request completing synchronously as if it had completed asynchronously. It just completes asynchronously before you even blin...
How do I prevent folders like My Pictures from being recreated?
Another converse of How do I programmatically create folders like My Pictures if they were manually deleted? and Why do folders like "My Pictures" come back after I delete them? is How do I prevent folders like My Pictures from being recreated? Starting in Windows 7, there is a group policy called Disable Known Folders which lets you specify a list of known folders which should be disabled. If somebody tries to create a known folder programmatically, the call will fail with . Note that this policy only blocks creation of the folder. If the folder already exists, then the policy has no effect. (You're l...
Racing email against a snail
The Windows team double-dogfoods Windows Server and Exchange Server, and while this is good for both products, it can be quite frustrating when something goes wrong. I remember back in the early days of the Windows 95 project, the mail servers once got so messed up that some email messages were not delivered for several days. After a colleague told me that he had just received an email message that I had sent several days earlier, I went to the library to look up the typical speed of a garden snail. (This was back in the days when you had to use an actual library to look up facts, and cat videos were avail...
The new research citation format, if students got to design it
References ¹ The Internets. ² Ibid. ³ Ibid.
How can I make a WNDPROC or DLGPROC a member of my C++ class?
Continuing my discussion of How can I make a callback function a member of my C++ class? Common special cases for wanting to use a member function as a callback function are the window procedure and its cousin the dialog procedure. The question, then, is where to put the reference data. Let's start with window procedures. The function and its close friend let you pass your reference data as the final parameter, prototyped as . As noted in the documentation, that value is passed back to the window procedure by the and messages as part of the structure. One of the first messages passed to a window is , s...
Why chicken wings dominate Super Bowl snack time
This upcoming Sunday is the biggest sports day of the year in the United States: The championship game for the professional American Football league. The entire country grinds to a halt. The most famous secondary effect of the game is the commercials. So many people watch the game that television advertisement costs are the highest for the Super Bowl, which means that companies will produce spectacular ads specifically for the Super Bowl, which means that more people watch the Super Bowl just for the ads. Another secondary effect of the Super Bowl is the spike in chicken wing sales. The United States chicken ...
Non-psychic debugging: If somebody's complaining that a collection should be empty but isn't, you might want to see what's in there
A programmer on the GHI team (yes, the same GHI team) reported that they were hitting an assertion failure using an internal library and asked for help debugging it. "Can somebody help me figure out which factory it is that did not get unregistered?" I didn't work on this internal library, but on the other hand I'm not afraid to look inside. Let's see what a looks like. No psychic powers needed here. I just followed my nose. The assertion says that a list is not empty. Therefore, we should look to see what is on the list. As a general rule, code is not intentionally written to be impossible to un...
Can process IDs be greater than 64000? Because we're seeing process IDs greater than 64000
A customer asked what to me was a very strange question. Can process IDs be greater than 64000? Because we're seeing process IDs greater than 64000. This is a strange question because the answer is right there: You're seeing process IDs greater than 64000 with your very own eyes. Do you doubt the evidence right there in front of you? It's like asking, "Is it possible to have an orange with no seeds? Because I have an orange with no seeds." We saw some time ago that process IDs can get very high indeed, although the kernel tries to keep the numbers small purely for cosmetic reasons. The customer explai...
One of my favorite error codes: Optional parameter missing
The error Optional parameter missing sounds awfully paradoxical, doesn't it. I mean, if the parameter is optional, why are you complaining that it's missing? This KB article explains why, specifically, the part that says, "If a parameter is omitted, the calling program must…". For those who don't want to click through, here's the deal: Methods described in a type library can declare parameters as optional. Optional parameters must come at the end of the parameter list, of course. The catch is how you programmatically invoke a method that contains optional parameters. If you want to call a method that h...
Why does my setup program detect the operating system incorrectly the second time I run it?
A customer reported that when their application called the function, it sometimes reported incorrect values. Specifically, the logs collected from clients shows that the first time the program was run on a Windows 7 machine, the operating system was correctly reported as 6.1.7600 (Windows 7), but the second time it was run, the operating system was erroneously reported as 6.0.6000 (Windows Vista). This was definitely strange behavior, and upon further questioning, the customer admitted that their application was a setup program. The fact that it was a setup program was the missing ingredient. What h...
The 2014/2015 Seattle Symphony subscription season at a glance
The pocket reference guide for 2014/2015.
How can I make a callback function a member of my C++ class?
Instead of a Little Program today, I'm going to answer a Little Question. This is a common beginner question, but I figure I'll just spell it out right here for posterity. First of all, you probably noticed that you can't do this: That's because the is declared as a so-called free function, but member functions are not free. Neither are function objects (also known as functors) so you can't use a as a window procedure either. The reason is that member functions and functors need to have a hidden parameter, but free functions do not have a hidden parameter. On the other hand, static methods are free fu...
Jan-Keno Janssen decides to rent a bicycle to get around Las Vegas; this is what happens
A different kind of run-around.
Non-psychic debugging: Looking for leaked objects by their vtable
A programmer on the GHI team reported that they were hitting an assertion failure using an internal library and asked for help debugging it. I didn't work on this internal library, but on the other hand I'm also not afraid to look inside and around. The assertion failure said, "Assertion failed: All widgets from a factory must be destroyed before you can unregister the factory." The factory does not keep a list of all the widgets it created. It merely keeps a count and asserts that the count is zero when the factory is unregistered." A good start would be to find the widgets that are still outstanding, ...
The Visual Effects dialog box just tells you what you want to hear
The Visual Effects dialog box has three options, "Let Windows choose what's best for my computer," "Adjust for best appearance," and "Adjust for crappiest appearance best performance." Some people have discovered the registry key where the Visual Effects dialog box remembers which radio button was most recently checked, but they found that when they programmatically manipulate the registry key, there is no effect on the actual visual settings. What's going on? What's going on is that the registry key is just there to tell you what you want to hear. It remembers which radio button you clicked, so that when you r...
Commissioner Bud Selig was named the first recipient of the Commissioner Bud Selig Leadership Award
In what was sure to have been a stunning surprise, last night, the first annual Commissioner Bud Selig Leadership Award was given out. And the winner was... Allan H. "Bud" Selig! I wonder who will win next year. Or who will win the Bud Selig Lifetime Achievement Award. Perhaps just to save time, they will name Bud Selig the Bud Selig Leadership Award Recipient For Life.
What clock do MSG.time and GetMessageTime use?
The structure has a field called which is a . There is also a function which returns a . Both are documented as returning the time the message was generated, but the types are different. Are these time units comparable? Yes, they are the same thing. They all use the 32-bit timer provided by the function. Sorry about the inconsistency in signed/unsigned-ness. Feel free to cast between them; they are fundamentally the same thing. Whether you prefer the signed or unsigned version depends on what you intend to do with the calculation, specifically, how you want to treat the case where the events occurred out...
When the Web page says that a tool is not supported, it means that if you find a problem and contact technical support, they're just going to point you back to the Web page
I file this under the category of People refuse to read what is right in front of them. There used to be a number of utilities available for download which all go by the name PowerToys. And they all contain text like this: Note: We take great care to ensure that PowerToys work as they should, but they are not part of XYZ and are not supported by Microsoft. For this reason, Microsoft Technical Support is unable to answer questions about PowerToys. This sentence isn't exactly in the fine print either. It's right there at the top of the page. This nevertheless does not stop a customer from contacting their su...
Hello Kitty takes a rather inefficient trip to the United States
In the book Hello Kitty Takes a Trip, the title character travels to New York, Florida, Vermont, and Hawaii, in that order. Now, sure, the Traveling Salesman Problem is NP-hard, but you're not even trying.
How do I get a high resolution icon for a file?
Jumbo size.
Psychic debugging: Why messages aren't getting processed by your message pump
The second parameter to the is an optional window handle that is used to tell the function to retrieve only messages that belong to the specified window. A filtered is nearly always a bad idea, because your program will not respond to messages that don't meet the filter. Unlike a filtered (which simply returns "no messages satisfy the filter"), blocks your thread and does not return until a satisfactory message arrives. Instead, they just pile up like newspapers on your doorstep. A common mistake I encounter is using a filtered as the main message pump: I don't know for sure, but I'm guessing that t...
The curse of the leading zero
Remember octal? I don't.
There are so many things that call themselves message queues
There are a whole bunch of things in Windows that call themselves message queues, and none of them have anything to do with each other. There is the window manager message queue, which holds window messages. And there is the Microsoft Message Queue (MSMQ) which is a networking technology for allowing multiple computers to communicate with each other by sending and reading messages. The Windows Mobile folks didn't want to feel left out, so they created their own Message Queue Point-to-Point message queue system. These are all unrelated technologies. Trying to, say, read window messages from a MSMQ message ...
How do I hit the Win+PrintScreen hotkey if my tablet doesn't have a PrtSc key?
Windows 8 added a new hotkey: Win+PrtSc takes a snapshot of your screen and puts it into the Screenshots folder of your Pictures library. But what if you are on a tablet with no PrtSc key? On tablets, you can perform the same operation by pressing Windows button + Volume down. Both of these are the hardware buttons on the tablet, not on any keyboard.
The Dead Grandmother/Exam Syndrome
A statistical analysis.
Creating a listview with checkboxes on some items but not others
Today's Little Program creates a listview with checkboxes on some items but not other. The extended style is really just a convenience style. Everything it does you could have done yourself, with a bit more typing. It creates a state image list consisting of an unchecked box (state 1) and a checked box (state 2). You could have done this yourself with followed by a few calls to . When you hit the space bar or click on the check box, the state image toggles between 1 and 2. You could have done this yourself by responding to (for the space bar), and the mouse notific...
How do I manually recalculate ACLs on a file based on the containing directory?
A customer wanted to move a file and have it forget all its old ACLs and instead inherit its ACLs from its new location. They found an old article of mine that said If you use to move a file and pass the flag, then it will not preserve the original ACLs on the moved files but will rather recalculate them from the destination's inheritable properties. (If you want to do the same thing in your own code, you can call the function, specifying that you want an empty, unprotected DACL.) They were having trouble implementing the recommendation in parentheses. We set the file to have an SDDL of in order to give ...
Can you dllexport/dllimport an inline function?
Yes, but it won't actually do much.
The case of the missing context menu verbs
A customer reported that when they right-clicked a batch file, a bunch of commands were missing. For example, Open was gone! Okay, there really isn't much of a story here, because some direct debugging quickly identified the culprit. The customer had installed a third party shell extension which returned a huge value from its method. Explorer told the shell extension, "Hey, like I've got room for 30,000 menu items. How many do you need?" The shell extension replied, "I'll take 29,995 of them." And so the shell extension sucked up nearly all the menu IDs, and by the time the Open command handler came along, ...
The case of the mysterious Alternate Data Stream query
A customer was running Windows Server 2003 ("Still in support until 2015!") and they have some custom application that monitors all disk accesses. They noticed that there were a lot of failed Alternate Data Stream queries coming from Explorer, and that was causing the custom application's logs to fill with largely useless information. These Alternate Data Stream queries are being made in order to extract file metadata for the pop-up infotip. (Windows later abandoned the use of Alternate Data Streams for file metadata since Alternate Data Streams were so fragile and were easily damaged or lost.) The customer fou...
Excuses college students use for missing assignments
My father recently retired after over 40 years as a college professor. During that time, he has seen all sorts of lame excuses students offer for missing homework assignments. Eventually, he got tired of dealing with them, so he instituted the following homework policy: There are nine homework assignments in this class, broken into three groups of three. I will take the best score from each group and drop the other two. Therefore, you can turn in as few as three homework assignments and still get full credit for homework. Late homework will be graded so you can learn from your mistakes, but the score will not c...
How do I obtain the computer manufacturer's name via C++?
The way to get the computer manufacturer and other information is to ask WMI. WMI is much easier to use via scripting, but maybe you want to do it from C++. Fortunately, MSDN takes you through it step by step and even puts it together into a sample program. But I'm going to write the code myself anyway. Today's Little Program extracts the computer name, manufacturer, and model from WMI. Remember that Little Programs do little or no error checking. And the smart pointer library we'll use is (rolls dice) ! Those include files and macros set things up so we can use to access WBEM interfaces. The fir...
What happened in real-mode Windows when somebody did a longjmp into a discardable segment?
During the discussion of how real-mode Windows handled return addresses into discarded segments, Gabe wondered, "What happens when somebody does a into a discardable segment?" I'm going to assume that everybody knows how traditionally works so I can go straight to the analysis. The reason is tricky is that it has to jump to a return address that isn't on the stack. (The return address was captured in the .) If that segment got relocated or discarded, then the jump target is no longer valid. It would have gotten patched to a return thunk if it were on the stack, but since it's in a , the stack walker didn'...
If the cursor clip rectangle is a global resource, how come I can't change it with ClipCursor?
A customer reported that the function was not working. "The cursor clip rectangle is a shared global resource, so I should be able to change it any time I like. My app installs a global mouse hook and sets the clip cursor inside the hook function, but the change doesn't have any effect. Why can't I change the clip cursor inside a mouse hook?" Sure, you can change the clip cursor inside a mouse hook. But remember, a shared global resource cuts both ways. Since anybody can change it, your app can change it any time it likes. But since anybody can change it, another app can also change it any time they like. In t...
We know your job is hard, you don't have to show us
Some years ago, I attended a internal presentation where one group was teaching another group how to use their new feature. This particular feature was a "Just plug in the things you want, click the Apply button, and sit back and relax while we figure out how to do what you asked" type of feature. The presentation leader showed some examples of the feature in action, and gave some clear, concise guidance on how the feature should be used, guidance like "Use Pattern A when the user is faced with a choice between two clear options, but use Pattern B when the situation is more open-ended." So far so good....
2013 year-end link clearance
Another round of the semi-annual link clearance. And, as always, the obligatory plug for my column in TechNet Magazine: The retirement of TechNet Magazine also spells the end of the Windows Confidential column, so this is the last of the obligatory plugs, at least until I have some other obligatory thing to plug.
New Year's Eve is sometimes a stressful occasion
Today is New Year's Eve, another opportunity for to mark that an approximately-integral number of revolutions of the earth have occurred since some point in time that wasn't even calculated correctly in the first place. (We retain it for backward compatibility.) December 31, 1999 was a particularly anxious day in the technology sector. Microsoft's Director of Y2K Readiness and vice president of Product Support Services described some of the steps that were being taken to prepare for any timekeeping-related issues that would arise as the calendar ticked over to 2000. We've analyzed phone capacity, IT systems ba...
There's no seating up there, so you just have to hang on for dear life
I dreamed that through a friend, I got to join a handful of other people atop Prince Charles's carriage as it wound its way through London. There was no seating up there, so you just have to hang on for dear life. When we reached Buckingham Palace, the assembled crowd and reporters swarmed the carriage for an opportunity to meet the Prince. This provided a sufficient diversion to allow us to climb down from the roof and sneak into the palace undetected. We've come to the end of the year, so that's all for Monday dream blogging. For those of you who hated it: You can uncover your eyes now.
How can I get the list of programs the same way that Programs and Features gets it?
A customer wanted to get the list of programs the same way that the Programs and Features folder gets it. Here, here's an idea: Instead of trying to mimic the Programs and Features folder, just ask the Programs and Features folder for its contents! That way, no matter what changes are made to how the Programs and Features folder obtains its contents (and those changes occur pretty often), your program will always match it, because you're just showing the same thing. Here's the basic idea, in scripting language since it's quicker: Okay, first of all, how did I get that magic string for the Programs and Feat...
Brief Q&A on the HeapEnableTerminationOnCorruption heap information flag
Question: What type of heaps are controlled by the flag? Answer: Any user-mode heap created by the function. This includes the process heap () but not the managed heap. Some components use under the hood. If so, then those heaps would also be affected. Question: What versions of Windows support ? Answer: The flag was introduced in Windows Vista and Windows Server 2008. It is also available on Windows XP Service Pack 3. In table form: Question: For operating systems that support it, under what conditions will termination on corruption be enabled? Answer: Question: What is the effect of setting the su...
I think we're going to be getting frozen leftovers for lunch today
There are a few times a year when a large fraction of employees are out on vacation at the same time, such as a single work day wedged between a holiday and a weekend (as happened this year on July 5). The most extreme case of this is the week between the Christmas holiday and New Year's Day, where the offices are practically empty. On these days of low demand, many services are scaled back and some choose to close entirely so that they can do inventory, perform routine maintenance, or upgrade equipment. One of the most visible service reductions is in food service. Smaller locations (such as snack bars) a...
Why is GetWindowLongPtr returning a garbage value on 64-bit Windows?
A customer was running into problems with their application on 64-bit Windows 8. They claimed that on Windows 8, the is returning a garbage pointer, which causes their program to crash. The same program works fine on 64-bit Windows 7. They asked the Windows team why they broke . An investigation of the customer's code quickly turned up the issue: See if you can spot the problem. The error is in the line that calls . It takes the 64-bit pointer value and casts it to a , which is a 32-bit integer type. This truncates the pointer and throws away the upper 32 bits of data. Therefore, when re...
The chain of stories triggered by seeing a package of Ahoj-Brause
While surfing the Web aimlessly doing valuable background research, I happened across a page that had a picture of a package of Ahoj-Brause (pronounced ahoy browse-uh). Seeing that package triggered a bunch of memories. My emergency vacation from several years ago included a visit to a friend spending the year at Uppsala University in Sweden. The following year, he invited one of his classmates (a student from Germany) to the United States to join his family for the Christmas holiday season. She brought with her some small gifts, among them a package of Ahoj-Brause. On its own, Ahoj-Brause is just a drink mix...
Essays from the funniest man in Microsoft Research
James Mickens has written a number of essays for ;login: magazine. The wall-of-text presentation is kind of scary, and the first time I encountered them, I skimmed the essays rather than reading them through. As a result, my reaction was, "I got tired." But if you follow the path and read the essays through, you realize that they are all brilliant. You can't just place a LISP book on top of an x86 chip and hope the hardware learns about lambda calculus by osmosis. and in the "so funny because it's true that it wraps around and isn't funny any more, but then wraps around a second time and is funny again, but ...
That doesn't sound like South Frisian to me
I dreamed that I was back in college taking a course in South Frisian, but I suspected something was up because the words didn't sound Germanic at all, and we were taught the words to a Christmas carol as Nom Yom Hear What I Hear? Also, because the course was taught by known prevaricator/exaggerator Robert Irvine.
Creating custom tasks on a jump list
Today's Little Program adds a custom task to the application's jump list. Take the scratch program and make the following changes. (Remember, Little Programs do very little error checking because that's how they roll.) This helper function creates an in-memory shell link object with the specified title, command line arguments, and icon. The underlying executable is assumed to be the running executable. When our window is created, we get the destination list for our application and ask it for an object collection so we can fill it with tasks. We empty the existing collection and add a single shortcut call...
Wouldn't the Recycle Bin sample program have been simpler without COM?
Steve Wolf suggests that the sample program would have been much simpler had the shell extension model been a flat Win32 interface. Okay, let's try it. Since this is an extension model, each extension needs to specify the callbacks for each namespace operation. Perhaps it could have been done like this: This would be the function that allows a third party to create a shell folder implementation. You pass it a bunch of flat callback functions, one for each operation that a shell folder supports, so that when the application tries to perform that operation on your custom folder, the operating system can as...
How do I display an RTL string in a notification balloon on an LTR system?
Suppose you have a program that is written in Arabic or Hebrew and you want to render some text. No problem. You just call and pass the flag to say, "Please render this string in an RTL context." Many other text-rendering functions have a similar flag, such as for . But what if you don't control the call to or or whatever other function is being used to render the text. If you don't control the call, then you can't pass along the magic "Please render this string in an RTL context" flag. If you're lucky, the component that is doing the rendering has some analogous flag that tells it to render in RTL cont...
Whether your application should display its content in RTL should be based on the content
A customer had the following puzzle: We have a small bootstrapper application that consists of a dialog box and a few message boxes. The problem is that we want our application to work properly on Arabic and Hebrew systems, and we can't come up with a good way to determine text direction of the underlying system. We found this article by Michael Kaplan that tells us how not to do it, which is great, but what's the recommended way of actually doing it? You already know whether you should be displaying your application's UI in LTR or RTL: If this is the Arabic-localized or Hebrew-localized version of your app...
Tales from "The Box": A survey of crackpots in physics
David Dixon, assistant professor of physics at Saddleback College, gave a presentation while he was at California Polytechnic State University titled Tales from "The Box", in which he presents selected contents of The Box, an archive of what is charitably describe as "unsolicited materials", but which is in more plain language "stuff sent to us by crackpots." (Warning: Sound quality is terrible.) He describes the various types of crackpots, common themes, behaviors that set off red flags in professional scientists, and how crackpot theories can be used in instruction. In the talk, he excerpts A Little Bit of ...
Why doesn't the New Folder command work in the root of a redirected drive resource in a Remote Desktop session?
When you connect to another computer via Remote Desktop, you have the option of injecting your local drives into the remote computer, known as Device and Resource Redirection. These injected drives are available under the UNC where X is a drive letter on the local machine. The name combines a bunch of internal technical terminology, so it makes perfect sense to the people who wrote it, but not as much to outsiders. (They may have chosen this name just to make themselves look smart.) The letters TS stand for Terminal Services, which was the former name of the technology now known as Remote Desktop. And the wo...
That fee was so that we wouldn't have to raise our prices
I dreamed that I got screwed by Ticketmaster. I was relieved when I woke up and found out it was only a dream. Bonus chatter: The economics of Ticketmaster. It reminds me of a company who added a service fee to an existing rate plan, and in their FAQ for the service fee, they explained, "That fee was so that we wouldn't have to raise our prices." This is some sort of bizarro-world logic. Yes, I know that this is so that the company can continue to advertise an artifically low "price" in all their marketing materials, and then make up the difference by tacking on a boatload of fees. A colleague of mine was pu...
Disabling the PrtSc key by blocking input
A customer asked how to disable the PrtSc key in the On-Screen Keyboard. There is no way to disable the PrtSc key in the On-Screen Keyboard. The On-Screen Keyboard shows a keyboard, and you can click any virtual key you like. There is no policy to remove specific keys from the On-Screen Keyboard. But this was a case of a customer breaking down a problem and asking a question about a specific part of the problem instead of presenting the entire problem so that a solution to the overall problem could be developed. The customer's real goal was to disable the PrtSc key in general. They had figured out how to d...
Turning off the disco lights on the Start screen
Blinky blinky.
How do you intercept taskbar notification balloons?
A customer wanted to know how they could monitor and intercept taskbar notification balloons. In particular, they wanted to intercept the clicks on a particular balloon and take alternative action. There is no supported mechanism for intercepting taskbar notification balloons or redirecting clicks on them. Imagine if that were possible: Fabrikam would intercept notification balloons for Contoso. If they had access to the balloon text itself, they might change the message from "Contoso products are back in stock. Click here to place your order." to "Special offer for Contoso customers: Take 10% off your first or...
Some vice presidents forget that not everybody attends the same meetings that they do
There are some vice presidents who forget that not everybody attends the same meetings that they do. When they send email to the entire division, they use buzzwords and acronyms that are not widely-understood. For example, they may mention the great progress that the Nosebleed team is making with DOXLA,¹ but that doesn't mean much to people who aren't on the Nosebleed team. Meanwhile, the people on the Nosebleed team probably don't know what the vice president is talking about when they compliment the Bunion team's recent breakthough in MT1 alignment.¹ When that happens, I like to send email back to t...
Mysterious email, possible social engineering, whatever it was, it didn't work
A colleague of mine got a strange piece of email. It went something like this, although I've substituted a fictitious nation and fictitious company name to protect the guilty(?). Subject: St. George's Island Embassy Trade Mission: Meeting request on behalf of Contoso Corporation Dear 〈name〉, I am contacting you following the advice of 〈senior executive〉, CTO of Microsoft Pangaea. The St. George's Island Embassy Trade Mission is currently assisting a local company, Contoso. Contoso would like to present 〈technology〉 to Microsoft. Details are in the attached document. Would...
This was only a test; if this had been an actual concert…
I dreamed that there was a fire in Benaroya Hall during a concert. The flames swirled overhead up by the ceiling. The exit doors had been blocked by security, so people flowed from door to door looking for a way out. Ha-ha, it was just a drill, and the flames were pyrotechnics. This dream brought to you by Great Ideas in Public Safety.
Destroying all child processes (and grandchildren) when the parent exits
Today's Little Program launches a child process and then just hangs around. If you terminate the parent process, then all the children (and grandchildren and great-grandchildren, you get the idea) are also terminated. The tool for this is the Job Object. Specifically, we mark the job as "kill on job close" which causes all processes in the job to be terminated when the last handle to the job is closed. We must therefore be careful not to allow this handle to be inherited, because that would create another handle that needs to be closed before the job is terminated. And of course we need to be careful not to...
Is it wrong to call SHFileOperation from a service?
A customer had a simple question: "Is it wrong to call from a service?" I don't know if I'd call it wrong, but I'd call it highly inadvisable. Update: See Is it wrong to call SHFileOperation from a service? Revised.
What’s up with the registry key HKEY_CLASSES_ROOT\CLSID\CLSID?
It's the class moniker.
What's the difference between the wParam of the WM_NOTIFY message and the idFrom in the NMHDR structure?
The message takes the following parameters: Notice that the identifier of the control sending the message appears in two places, once in the and again in the . What's the difference? There is no difference. It's just a convenience. The same value is passed in both places, and you can check whichever one is easier for you. You might use the because it avoids having to dereference a pointer. You might use the because that way you have only one thing to pass to your helper function. Whatever floats your boat. Passing the same information multiple ways is hardly new. The message also passes redundant inf...
Sir, is this your high-speed ferry?
The Victoria Clipper is a high-speed ferry that runs primarily between Seattle and Vancouver Victoria, BC. Early Sunday morning, a man scaled a fence and drove off with one of the boats. The issue was resolved without major incident and only minimal damage, which means that it is now open season on jokes! "Why yes, officer, this is my ferry. I must have left the registration in my other pants." According to the vessel superindendent, "There is a joystick and he thought it was like an Xbox," ending up driving the boat in circles. You can see the GPS track here (photo 19). Of course, if the thief had had a K...
How do I configure the timeout used by UI0Detect (Interactive Services Detection service)?
Windows Vista introduced Session 0 Isolation which enforces the rule that services should not display UI. If a service tries to display UI, another service known as the Interactive Services Detection service detects this situation and signals the user that a service wants to display UI and gives the user an opportunity to switch to the service desktop, respond to the UI, and then switch back. If the user ignores the service for about one minute, it switches back automatically, on the assumption that something went bad with the detection and the service is actually finished with its UI. (That way, the user ...
The walls of my friend's house sometimes randomly got corrupted
One evening, I had a series of three dreams. In each one, I visited an unusual home. In the third dream, I visited the home of a friend of mine. He lived in a white stucco split-level, a stereotypical suburban home. What made the house interesting was that if you did things just right, dark dots would appear on the wall and slowly consume it. My friend explained, "This house is running a very old build of DirectX, and sometimes it just does that." We set up a repro and calculated that when the dots appeared, stack usage was exactly 5124 bytes. This was a 16-bit house, and the stack overflow into the heap cause...
Logging the foreground process as it changes
Today's Little Program simply logs all changes to the foreground window by recording the path to the application the user switched to. You might use this as part of a usability study to monitor what applications users spend most of their time in. Most of this code is just taking things we already know and snapping them together. Using accessibility to monitor events, specifically to monitor foreground changes. to get the process ID from a window. to get a handle to a process given the process ID. to get the path to the application from the handle. (For Windows XP, yo...
Notes on gift card and gift certificates in the state of Washington
Today is the unofficial start of the holiday shopping season. One of my colleagues read the fine print of a gift card he received: A monthly maintenance fee of $3 applies but is waived for the first twelve months after the card is issued. Thereafter, monthly maintenance fees are waived for an additional three months if the card is used in any given month. This seems kind of backwards. They charge a maintenance fee if you don't create any work for them. Shouldn't the maintenance fee be charged when you use the card, rather than when you don't? This "maintenance fee" is really just an "account inactivity fee". ...
Why can't I create my dialog with DialogBox, DialogBoxParam, CreateDialog, CreateDialogParam, or the indirect versions of same?
One of the purposes of my dialog manager series was to help people diagnose problems with their dialog boxes. But since I embedded the tips inside the series body, it's hard for people to find them, and I still end up answering the same questions over and over. So here it is in a separate article that hopefully people can find. Why your call to or is failing. This also goes for , but perhaps extra so because the MFC source code says even though the problem is rarely due to an error in the template. A wrong comment is worse than no comment at all.¹ I've decided to put the reasons in most-likely-e...
Things that can happen when your kitchen gets taken over by others
Today is the Thanksgiving holiday in the United States, one of the the major holidays for family get-togethers. (Another big one is Christmas.) One year, it was our family's turn to host Thanksgiving, and when that happens, it means that the kitchen is overrun by relatives cooking all the dishes and hunting through the cabinets and drawers of an unfamiliar kitchen. One year, I learned that a pastry blender can be used as a potato masher and that a cheese planer can be used as a pie server. This is what happens when other people use your kitchen. It could also mean that my kitchen has too many froofy gadgets. ...
If you try to declare a variadic function with an incompatible calling convention, the compiler secretly converts it to cdecl
Consider the following function on an x86 system: The function declares itself as , which is a callee-clean convention. But a variadic function cannot be callee-clean since the callee does not know how many parameters were passed, so it doesn't know how many it should clean. The Microsoft Visual Studio C/C++ compiler resolves this conflict by silently converting the calling convention to , which is the only supported variadic calling convention for functions that do not take a hidden parameter. Why does this conversion take place silently rather than generating a warning or error? My guess is that it's...
The case of the DLL that refuses to load
A customer reported that they had a problem that occurred only on some machines but not others. Their application called and the call succeeded on some machines, but failed on others with error ("The specified module could not be found"). The path was a fully-qualified path to a file that was confirmed to exist and be readable. If the command was used in the debugger to break when the DLL loads, the breakpoint does fire, but a breakpoint on Contoso's is never hit. "I think this means that the problem is not that Contoso failed to initialize, but what does it mean?" If you get a break from but no brea...
Why did Raymond bring a knitting bag to every meeting?
I stopped knitting a few years ago, but back when I knitted regularly, I tended to bring my knitting bag with me everywhere I went. There are a lot of idle minutes in your typical day. Waiting for the bus, waiting in line for the ATM, waiting for a meeting to start. There's not enough time in those idle minutes to do anything substantial, but it's enough time to sneak in a little bit of knitting. But there's another reason I brought a knitting bag to every meeting. Nothing says "I don't care about this meeting" like knitting.
My friend lived in an apartment inside a museum
One evening, I had a series of three dreams. In each one, I visited an unusual home. In the second dream, I visited the home of a friend of mine. She lived in a modern luxury apartment inside an art museum. It was a little tricky, because you could visit her only during museum hours. If you stayed past closing time, then you were locked inside the museum, and you were spending the night whether you liked it or not. On the other hand, it meant that you could go out an view the art to your heart's content without any crowds. And no, the museum did not come to life. You just got free run of a museum for the nigh...
Extracting GPS coordinates from a photo and plotting it on a map
Today's Little Program extracts GPS coordinates from a photo and plots it on a map. Remember, Little Programs do little to no error checking, because that's how they roll. We start with a simple function that takes a latitude and longitude and opens a Web page that highlights that coordinate. In a real program, you probably would do something more interesting with the coordinates, but I'm opening a Web page just to do something. The class is an incredibly lame wrapper around for RAII purposes. The function is where the real work happens. GPS latitude and longitude are encoded in the shell property sy...
How do I get the effect of CW_USEDEFAULT positioning on a window I've already created?
A customer wanted to know how to get the effect of positioning on a window that already exists. In particular, they wanted to be able to reposition a dialog box to get the cascade effect, but since you can't actually pass in a dialog template, the repositioning has to be done after the fact. (Presumably in the handler, which runs before the dialog is visible, so that there is no visible flicker.) The solution here is simple: Create a temporary invisible window with as its position and the same height and width as your dialog box. See where the window manager puts that temporary window and move your dialog...
How do I get the path to the default user's profile?
A customer wanted to know how to get the path to the default user's profile. On older versions of Windows, the default location of the default user's profile was . Then it moved to . Now it's in . And the location may have been customized, so in principle it could be anywhere. The function to get the default user profile's directory is is the deviously-named . But the reason I'm writing this article is not to call your attention to the function, but rather to something in the function documentation. The documentation for the function includes the strings and , so all somebody had to do was type either of ...
Why don't all of my documents show up when I arrange my Documents library by Name?
A customer reported that when they opened their Documents library on Windows 7, some files were missing if they selected Arrange by: Name or Arrange by: Author or in fact any arrangement other than Arrange by: Folder. What's going on? When you arrange the Documents library by anything other than Folder, the Documents library uses the content indexer to obtain results quickly, rather than kicking off a recursive disk search (ugh). (The Folder arrangement does not require a recursive search, so it can use the traditional / loop to get the results. A member of the search indexer team suggested that a common ...
Why is the Program Files directory called Program Files instead of just Programs?
Some people suggest that one thing Microsoft Research could do with that time machine they're working on is to go back in time and change the name of the Program Files directory to simply Programs. No, it really should be Program Files. Program Files are not the same as Programs. Programs are things like Calc, Notepad, Excel, Photoshop. They are things you run. Program Files are things like and . They are files that make programs run. If the directory were named Programs, then people who wanted to run a program would start digging into that directory and seeing a page full of weird DLL names and wonder "W...
My friend lived in a tiny house with an enormous garage
One evening, I had a series of three dreams. In each one, I visited an unusual home. In the first dream, I visited the home of a friend of mine. But instead of living in his condominium in the city, he lived in a house built into the side of a cliff. The house commanded a breathtaking view of the valley below, but the living quarters weren't very large. This was to his liking. "Moving in didn't take long." The top floor was a single room the size of a typical bedroom. The bottom floor was half that size. There was a six-inch-square mesh of wire covering the downstairs walls. "That lets the dog roam freely down...
How can I launch an unelevated process from my elevated process and vice versa?
Going from an unelevated process to an elevated process is easy. You can run a process with elevation by passing the verb to or . Going the other way is trickier. For one thing, it's really hard to munge your token to remove the elevation nature properly. And for another thing, even if you could do it, it's not the right thing to do, because the unelevated user may be different from the elevated user. Let me expand on that last bit. Take a user who is not an administrator. When that user tries to run a program with elevation, the system will display a prompt that says, "Hey, like, since you're not an ad...
Restoring symbols to a stack trace originally generated without symbols
Has this ever happened to you? Ugh. A stack trace taken without working symbols. (There's no way that is a deeply recursive 60KB function. Just by casual inspection, you know that the symbols are wrong.) To see how to fix this, you just have to understand what the debugger does when it has no symbols to work from: It uses the symbols from the exported function table. For every address it wants to resolve, it looks for the nearest exported function whose address is less than or equal to the target value. For example, suppose has the following exported symbols: Look at it this way: The debugger is gi...
Why is my FormatMessage call crashing trying to read my insertion parameter?
A customer was looking for assistance in debugging a crash in their product. The stack trace looked like this: The string being formatted is , and the insertion is a long (but valid) string. A unit test which passes a similarly long object name to does not crash. What is the problem? There are clues in the stack trace. The natural place to start is the function that calls to see what parameters are being passed in. And that's where you see something strange: (The clue in the stack trace was the word fallback in the function name, which suggests that if the formatting attempt fails, it'll try again som...
A possibly unbeatable record for the shortest amount of time between an email message and its resend
I occasionally bring up the issue of people who ask a question and then repeat the question, especially people who repeat the question with some impatience. At the time, the record for the shortest time between the message and its repeat was eight minutes. But I think I have something unbeatable. From: X To: ABC Team I hit this crash in ABC. Can somebody take a look at it? A half hour later, somebody replied: From: A To: X, ABC Team This looks like the problem is really in the DEF component. You should have the DEF team look at it. Person X waited a few hours, then got impatient. From: X T...
Microspeak: Spinning up or kicking off a build
Round and round.
How did Raymond discover his carrier-screaming talent? And his homemade Marauder's Map
George wonders, "I am curious how Raymond found about his talent. Maybe it will be an interesting post." This isn't like a superhero who discovers as a young adult that he has powers beyond that of mortal men. And there was no radioactive spider. It was a simple case of problem-solving. The basic way of checking whether the mainframe was up was to go into the lab and see if the terminals responded. But of course this meant having to hang around in the lab building all day. The next way of checking whether the mainframe was up was to stay in your dorm room doing some other work while listening to a portable ...
What's the point of the various …WhenCallbackReturns functions?
The thread pool provides a number of functions named . What's the point of all these functions? Why can't you just do the operation yourself immediately before returning? We saw last time. What's the point of the others? Basically, the same thing as . It's a way to release a resource after execution has left the function and the callback is marked as complete. In the case of a synchronization resource, that resource may be what's keeping somebody from unloading your DLL, or it might protect a race condition between the callback function and a function that tries to cancel the callback.
Partially eliminating the need for SetThreadpoolCallbackLibrary and reducing the cost of FreeLibraryAndExitThread
Update: Daniel points out that there is still a race condition here, so this trick won't work. Rats. The documentation for the says This prevents a deadlock from occurring when one thread in DllMain is waiting for the callback to end, and another thread that is executing the callback attempts to acquire the loader lock. If the DLL containing the callback might be unloaded, the cleanup code in DllMain must cancel outstanding callbacks before releasing the object. Managing callbacks created with a that specifies a callback library is somewhat processor-intensive. You should consider other options for en...
CoUninitalize will ask a DLL if it is okay to unload now, but the answer is a foregone conclusion
The entry point is exported by COM in-proc servers. COM host applications call periodically to ask COM to do DLL housecleaning, and in response, COM asks each DLL if it is okay to be unloaded. If so, then COM unloads the DLL. What is not well-known is that COM also does DLL housecleaning when you shut down the last apartment by calling . When that happens, COM will still go around asking each DLL whether it's okay to be unloaded, but the question is merely a formality, because regardless of your answer, COM will unload you anyway. The story here is that COM is being shut down for the process, so COM knows ...
What is the point of FreeLibraryAndExitThread?
The function seems pointless. I mean, all the function does is Who needs such a trivial function? If I wanted to do that, I could just write it myself. And then you discover that occasionally your program crashes. What's going on? Let's rewind and look at the original problem. Originally, you had code that did something like this: This worked great, until somebody did this to your DLL: This code fragment calls your function and then immediately unloads the DLL, presumably because all they wanted to do was call that one function. Now you have a problem: That call frees your DLL, while your i...
The complexity of modern voting, or at least modern dream voting
I dreamed that I arrived at my polling station just before it closed, but the ballot was not what I expected. Instead of voting on political candidates or referenda, I was voting on music from the 1980's. I ended up voting for an Anne Murray song because it was the only one I recognized, and it wasn't a bad song.
Manipulating the zone identifier to specify where a file was download from
When you download a file via Internet Explorer, the file is tagged with a little bit of information known as a zone identifier which remembers where the file was downloaded from. This is what tells Explorer to put up the "Yo, did you really want to run this program?" prompt and which is taken into account by applications so that they can do things like disable scripting and macros when they open the document, just in case the file is malicious. Today's Little Program is really three Little Programs: One to read the zone identifier, one to set the zone identifier, and one to clear it. The first program takes...
On the various ways of getting the current time and date in Win32
There are a number of functions in Win32 that obtain the current date and time. Here's how they fit together: The starting point is . This returns the current time in UTC in the form of a structure. This also happens to be the time format used internally by the system, so this value can be retrieved with a minimum of fuss. You can also call which returns the current UTC time in the form of a structure. To do this, the operating system takes the current and then calls the moral equivalent of , which does a boatload of gnarly math to decompose the into year, month, day, hour, minute, second, and milliseco...
The guide to trading candy
Important information to know this evening.
If there is no 16-bit emulation layer in 64-bit Windows, how come certain 16-bit installers are allowed to run?
Because they are emulated.
Distinguishing between asking for help with a product and asking for help with a product's installation
Internally at Microsoft, we have a programmer's tool which I will call Program Q. On the peer-to-peer mailing list for Program Q, somebody asked the following question: What's the best way to look at all tables created in the past week? I want to repeat this command across multiple table repositories. Somebody chimed in with the answer. You are looking for something like . If you want to repeat across multiple table repositories, you would say , replacing with the table repository server name. This seemed to work, but there was a follow-up question: What's the best way to get the repository se...
Help me optimize this code which enumerates all possible GUIDs
Um, not really.
The financial acumen of sea turtles
I dreamed that I was attending some sort of "how to be awesome" seminar where the presenter said, among other things, that a sea turtle, when left to thrive undisturbed, amasses $1 million in personal wealth within one year.
Using GetLogicalProcessorInformationEx to see the relationship between logical and physical processors
Today's Little Program uses the function to print the mapping of logical processors to physical processors, as well as the mapping of logical processors to packages. (A dual-core processor is a single package with two cores. If those cores are themselves dual-hyperthreaded, then you have four logical processors total.) The helper function takes a typed pointer and adds a byte offset to it. This is just a typing-saver function. Enumerating logical processor information is complicated due to the variable-size structures, so I wrap it inside this helper enumerator class. Construct it with the relationshi...
My, those threads start up really fast nowadays
Here's a little puzzle inspired by an actual bug: Can the assertion at the start of ever fire? Naturally, the answer is Yes, otherwise it wouldn't be a very interesting article. The assertion can fire if the worker thread starts running before the call the returns. In that case, the caller hasn't yet received the handle or ID of the newly-started thread. The new thread calls , which returns since hasn't been initialized yet. The actual bug was something along the lines of this: If the new thread started up so quickly that the original thread doesn't get a chance to receive the new thread ID and p...
When should I use the FIND_FIRST_EX_LARGE_FETCH flag to FindFirstFileEx?
Windows 7 introduces a new flag to the function called . The documentation says that it "uses a larger buffer for directory queries, which can increase performance of the find operation." This is classic MSDN-style normative documentation: It provides "just the facts". Far be it for MSDN to tell you how to write your application; the job of function-level documentation is to document the function. If you want advice, go see a therapist. If the reason why you're calling is to enumerate through the entire directory and look at every entry, then a large buffer is a good thing because it reduces the number o...
It rather involved being on the other side of this airtight hatchway: Planting DLLs into directories on the PATH for applications whose current directory is always System32
Big PATH attack.
The hierarchy of user education, as interpreted by a vice president
One of my colleagues told me a story from his days on the Windows team. He had to give a presentation to his vice president on his feature, and he prepared his presentation and demo obsessively to make sure it went smoothly. At the meeting, there were three presentations on the schedule, all of them with features targeting IT professionals. The first presenter got up and walked through their feature. Upon reaching a particular tricky part of the feature, the vice president asked, "How are customers going to know how to set up those parameters?" The presenter explained, "We'll have a whitepaper explaining how to...
Using a toy cash register as a keyboard doesn't add up
I dreamed that I was composing a blog entry about one of my dreams, but I had to do it on a toy cash register which had been paired to my computer. It turns out that this is difficult for a number of reasons. For one thing, the cash register has only ten letters of the alphabet on it. You have to switch to the alternate keyboard for the rest. Also, there is a backspace key but no other editing keys. Finally, there is a key labeled ≔ which changs the formatting to multi-person mode. Okay, this doesn't actually make typing more difficult, but it's still something unusual.
Opening and manipulating Internet Explorer windows programmatically
Today's Little Program takes the JavaScript application from a few years ago and converts it to C#. This was inspired by a customer who started with the question, "How can I close all Internet Explorer windows programmatically?" This was a strange request. After all, the user may be rather upset that their Amazon shopping spree was suddenly terminated mid-stream. Upon closer questioning, the customer explained that they had a business process which, among other things, opened a bunch of Internet Explorer windows, and when the operation was over, they wanted to close the windows. Okay, so they didn't reall...
The case of the redirected standard handles that won't close even though the child process has exited (and a smidge of Microspeak: reduction)
A customer had a supervisor process whose job is to launch two threads. Each thread in turn launches a child process, let's call them A and B, each with redirected standard handles. They spins up separate threads to read from the child processes' stdout in order to avoid deadlocks. What they've found is that even though child process A has exited, the threads responsible for monitoring the output of child process A will get stuck in the until child process B also exits. The customer further reported that if they added a brief call between creating the thread that launches child proces...
What is the inverse of AdjustWindowRect and AdjustWindowRectEx?
We saw over a decade ago (my goodness I've been doing this way too long) that the and functions do not take menu wrapping into account because they don't take a window handle parameter, so they don't know what menu to test for wrapping. Still, they are useful functions if you aren't worried about menu wrapping because they let you do window size calculations without a window handle (say, before you create your window). But those functions take a proposed client rectangle and return the corresponding non-client rectangle by inflating the rectangle by the appropriate borders, caption, scroll bars, and other n...
Why does my window get a WM_ACTIVATE message when it isn't active?
Say you launch a program, and for whatever reason the program takes a long time to start up, so you start doing something else, say launching Calculator and balancing your checkbook. Eventually, the program you launched a while back gets itself off the ground and creates its main window. And the window sits in the background (since the window manager won't let it steal foreground activation), but the caret is blinking in the edit control, and the program seems to think it's the active window. If you write a test program to do this, say by sticking a at the start of your , you'll see that your window gets a mes...
Just because I don't deny something doesn't make it true
There are a number of tricks people try to pull, and I hate them. Today's trick is one of the many varieties of the BCC trick (sometimes less surreptitiously—but still annoyingly—done as a CC trick). Occasionally, I will be quietly added to an email discussion, typically via BCC, without any indication as to why I was added. After reading the discussion (which can be quite lengthy), I realize that they are pulling the "Raymond didn't deny this, so I'll assume this is true" trick. They are adding me as a way of obtaining my approval for a claim made in the discussion. "The Widget does not immediatel...
The imaginary experience of dining at an underground restaurant
I dreamed that my brother complained, "Dude, you didn't leave room for my car in the garage." Well yeah, because I didn't know you were coming. We decide to go out for dinner, and I see that he squeezed a third car into our two-car garage. We back out, and I watch the car fit through a gap of two feet between my car and the garage door. We drive around and decide to eat at an underground restaurant at the home of my retired next-door neighbors (across the street in real life at my old house). At this point, my dinner partner changes to a former work colleague. Without prompting, she tilts her head back, and he...
Filtering the folders that appear in the Browse for Folder dialog
IFolderFilter.
C++ corner case: You can implement pure virtual functions in the base class
In our discussion , we saw that you can declare a pure virtual function with the syntax, and if you try to call one of these functions from the base class, you will get the dreaded R6025 - pure virtual function call error. In that article, I wrote that a pure virtual function is "a method which is declared by the base class, but for which no implementation is provided." That statement is false. You can provide an implementation for a pure virtual method in C++. "That's crazy talk," I hear you say. Okay, let's start talking crazy: What happens when the function constructs a ? Trick question, becau...
Happy 110th birthday, Professor Alyea
Professor Hubert Alyea would be 110 years old today, if he were still among us. (He passed away in 1996 at the ripe age of 93.) LIFE magazine called him the science teacher you wish you had for his engaging (and often explosive) chemistry demonstrations. He was called an "international grand master of lecture demonstrations" by Bassam Shakhashiri, noted chemist and author of several books on chemical demonstrations. I had the immense good fortune to attend one of his lectures. As he prepared his equipment, he casually popped a piece of dry ice in his mouth. (DO NOT TRY THIS AT HOME.) You can see a demonstrat...
How do I find out what size the window manager would have chosen for my window?
We saw some time ago how the window manager decides where to place a newly-created window if you pass the values when creating the window. But what if you want to filter the values first? If you pass an explicit upper left corner but pass for the width and height, then the bottom right corner will be down near the bottom right corner of the screen. Given that your code is buggy, is there a way I can ask how big you would have made the window, so I can go in and fix your mistake? If I try to resize it after the fact, there's an ugly flicker. I'm kind of disgusted that something this simple still doesn't work ...
Using the TAB key to navigate in non-dialogs, redux
You want to use the TAB key to navigate through a non-dialog, so you call in your message loop, but it doesn't work! The problem here is that you are passing the wrong window handle to . The first parameter to is the dialog-like window you want to be able to navigate through. But the code above passes the window that received the message, so you are basically telling the control to do TAB navigation within itself. And naturally, the result of that is that focus stays where it is, because if you ask a button, "Hey, could you move to your next tab stop?" the button is going to say, "Dude, I'm the only tab st...
I wrote my thesis on an airplane, for heaven's sake
As I wrote today's story, I recalled that I wrote the bulk of my thesis on an airplane. In longhand. Microsoft flew me out for an interview, so I had to endure two cross-country plane trips. I scheduled the interview on a Monday so that I would miss only one day of class, and among the things I brought with me was a notepad, which started the trip blank. I wasn't sure why I brought it, but I was sure it'd come in handy. And then I realized that I had a lot of time to kill, what with spare moments on the ground, in the air, back on the ground, waiting for my next interview, whatever. And during that time, I wro...
I wrote FAT on an airplane, for heaven’s sake
When you wrote code for 16-bit Windows, one of the things you spent time doing as part of performance tuning was deciding which functions should be grouped together in which segments. Code in 16-bit Windows executed out of code segments, each of which could be up to 64KB in size. When a code segment was loaded from disk, the entire segment was loaded, and when it was discarded, the entire segment was discarded. This meant that you could affect your application's performance in significant ways by choosing which functions go in which segments. For example, it was to your advantage to keep functions that are call...
But instead, they decided to build the Great Wheel
I dreamed that Seattle was building its own version of the Eiffel Tower. Just like the original, except that it was also a thrill ride similar to Round Up but you are seated. It turns out that the city of Seattle accepted my subconscious's instructions to replicate another city's famous landmark, but the message wasn't received loud and clear. Instead of making an Eiffel Tower knock-off, we decided to make a London Eye knock-off.
Printing the contents of the clipboard as text to stdout
The takes its stdin and puts it on the clipboard. But how do you get it out? That's today's Little Program. (I guess we could call it .) Okay, what do we have here? We open the clipboard and try to get the Unicode text on it. We then look for the null terminator within the first 0x10000000 bytes. Why do I stop at 256MB? Because I'm lazy and this lets me avoid worrying about integer overflow. This is a Little Program, remember. If you pass the command line switch, then the output is printed to stdout as the Unicode string itself. If you pass the command line switch, then the output is converted to AN...
What's the difference between CopyIcon and DuplicateIcon?
There are two functions that can be used to create one icon that is identical to another. One of them is . The other is . What's the difference? There isn't any difference. Both functions clone an icon. In fact, their implementations are basically line-for-line identical. Originally, there was just one function to clone an icon: . Windows 3.0 introduced Program Manager, and the developers of Program Manager wrote their own function called . Why? I have no idea. My guess is that they didn't realize that such a function already existed, so they inadvertently reinvented the wheel. Windows NT 3.1 came a...
The relationship between module resources and resource-derived objects in 32-bit Windows
Last time, we saw how 16-bit Windows converted resources attached to an EXE or DLL file (which I called module resources for lack of a better term) to user interface resources. As a refresher: During the conversion from 16-bit Windows to 32-bit Windows, some of these rules changed. Specifically, icons, cursors, and accelerator tables are no longer references to the resource. Instead, the resource is treated as a template from which the actual user interface resource is constructed. Uh-oh, what's up with those asterisks? Let's start with accelerator tables. In order to simulate the reference semantics of 16-...
The relationship between module resources and resource-derived objects in 16-bit Windows
As we saw last time, in 16-bit Windows, resources attached to an EXE or DLL file (which I called module resources for lack of a better term) were recorded in memory as discardable global memory blocks, and the window manager accessed them directly as needed. For example, if you had an icon or a cursor, the or was really a resource handle, and when the window manager needed to draw the icon or cursor, it would cast the icon or cursor handle to a global handle (since that's what it was under the hood), then call to access the raw resource data in order to copy the pixels onto the screen. Similarly, accelerator...
The management of memory for resources in 16-bit Windows, redux
Some time ago, I briefly ran down how 16-bit Windows managed memory for resources. But there's a detail that I neglected to mention: Ownership. As we saw, a resource handle was really a pointer to the resource directory entry of the resource from the corresponding module. This could be done with a 16-bit pointer because the segment portion of the pointer could be inferred from the module the resource belonged to. In fact, since modules could be relocated in memory at run time due to compaction, you had better not try to remember the segment portion of the pointer since it could change! The function located t...
Sometimes my dreams are entirely uneventful
I dreamed that I was washing dishes with my lovely wife.
Playing a sound every time the foreground window changes
Today's Little Program plays a little sound every time the foreground window changes. One of my colleagues wondered if such a program was possible, "so that I stop accidentally typing the second halves of paragraphs into windows that pop up and steal focus." It's not clear whether this program will actually solve the bigger problem, but it was fun writing the program, and maybe you can use it for something. This program installs an accessibility hook that listens for changes to the system foreground. And when it happens, we play a little sound. I chose the Windows 7 Speech Misrecognition sound because ...
2013 Q3 link clearance: Microsoft blogger edition
It's that time again: Linking to other Microsoft bloggers, and once again, the links are all from the excellent NT Debugging blog.
How can I determine how responsive my application is to input?
A customer was adding diagnostics to their application and wanted to know if there was a way to detect that the application was being slow in processing its input. These sorts of delays manifest themselves to the end user as a sluggish application which is slow to respond to input events. They already had a watchdog timer that was reset every time their call returned a message, so they could capture stack traces if their application stopped processing messages for more than X milliseconds. They wanted to extend this diagnostic information to input delays. Fortunately, there's an easy way to tell. The wil...
Don't forget, Unicode includes formatting characters which can be used to influence output formatting
Consider this simple function: Depending on your screen resolution and font choices, this may end up displaying like this: That line break was awfully unfortunate, stranding the number 2 on a line by itself. (In publishingspeak, this is known as a orphan.) You can't control where the function will insert line breaks, but you can try to influence it with the use of Unicode formatting characters. Here, we can change the space before the 2 to a Unicode non-breaking space, U+00A0. The result is slightly less awful. Unfortunately, I haven't had much luck with the soft hyphen, but the zero-width space...
How can I tell that somebody used the MAKEINTRESOURCE macro to smuggle an integer inside a pointer?
Many functions and interfaces provide the option of passing either a string or an integer. The parameter is formally declared as a string, and if you want to pass an integer, you smuggle the integer inside a pointer by using the macro. For example, the function lets you load an resource specified by integer identifier by passing the identifier in the form . You can tell that it was the resource-loading functions who created the macro in the first place, since the name of the macro is "make integer resource." But other functions use the convention, too. The function lets you obtain a function exported by ord...
Punctuation is becoming increasingly decorative and less functional
The "Blog" of "Unnecessary" Quotation Marks calls out abuse of the quotation mark. For some reason, quotation marks are being increasingly used as a form of emphasis (a usage which remains controversial), by people unaware that such use, when interpreted as scare quotes, serves to undermine their original point. Mind you, the emphasis theory doesn't explain all misuses of quotation marks I've seen. I'm led to believe that some people simply enjoy seeing quotation marks and place them around randomly-selected words. Apostrophes are another commonly-misused punctuation mark. So much so that the city of Birmin...
Wait, so does moving a file recalculate inherited permissions or doesn't it?
A customer had a question about whether moving a file recalculated inherited permissions. They found that on their Windows Server 2008 R2 machine, if they moved a file between directories with different inheritable ACEs, then the security descriptor is recalculated to match the destination folder, if they perform the move from the machine itself. The same thing happens if they go to a machine running Windows 7, However, if they repeat the experiment from a machine running Windows XP or Windows Server 2003, then the security descriptor is preserved across the move. The customer is confused. Why doe...
I dreamed that I was in an alternate-universe Samuel L. Jackson movie
I dreamed that I was part of the crew of an underwater spaceship, and we had to deal with an alligator that got on board. How the alligator got on board was never explained, but now is not the time to ask questions because, you know, alligator. The plan was to flood the ship and wash the alligator out. There were only enough air pills for the female crew members. The men would have to hold their breath and hope for the best, with the expectation that not all would make it. But before we could execute the plan, the door caved in and the ship began to fill with water. At this point, I transferred to another dream...
Providing a custom autocomplete source for an edit control
Today's Little Program shows a custom source for autocomplete. It's nothing exciting, but at least's it's something you can use as a starting point for your own customizations. We start with a dialog template, whose edit control will be the target of a custom autocomplete. Just for fun, I wrote the program in ATL. Instead of complaining that my code is hard to understand because I didn't use an application framework, people can now complain that my code is hard to understand because I used the wrong application framework. To save some typing, I define a shorthand name for "the predefined ATL object for e...
How can I tell that I have a shell folder that represents My Computer?
You have in your hands an , and you want to know whether this is an that represents My Computer. There are a few ideas that may occur to you. One is to ask the folder for its current location and compare it to . Okay, we have a lot of moving parts here. Let's look at them one at a time. The function takes an object and asks what folder it represents. Since we don't actually use any methods on the object beyond what is provided by , we weaken the parameter requirement to simply . The function compares two absolute ID lists according to the criteria specified by the . The combines these two function: It...
Raymond's subjective, biased, unfair, and completely wrong characterization of the sounds of several East Asian (and one Southeast Asian) languages
Hokkien: This is the language I learned first, so to me it sounds perfectly normal and is in fact how languages should sound. I find it odd that people describe it as one of the more difficult languages to learn. I mean, sure it has a large tone repertoire (eight theoretical, though only seven in practice) and extensive tone sandhi, but that's what makes it beautiful and smooth. And what's so hard about having unvoiced aspirated consonants, unvoiced unaspirated consonants, and voiced consonants? Mandarin: Mandarin is the German of East Asian languages: It is harsh and unforgiving. There are only four formal ton...
When a program is launched via DDE, and there are multiple servers, which one is used?
Although you are more than welcome to stop using DDE (please oh please stop using it), there are still many applications which still use it (cough), and as a result, customers still have questions about it. One customer wanted to know why, if multiple copies of a DDE-based application are running, Windows 7 will send the command to the earliest-launched copy of the program, whereas Windows XP will send the command to the most-recently-used copy. "Our employees were used to forcing the document to open in a specific window by switching to that window, thereby making it most-recently-used, then switchin...
SubtractRect doesn't always give you the exact difference
The function takes a source rectangle and subtracts out the portion which intersects a second rectangle, returning the result in a third rectangle. But wait a second, the result of subtracting one rectangle from another need not be another rectangle. It might be an L-shape, or it might be a rectangle with a rectangular hole. How does this map back to a rectangle? The documentation for says that the function performs the subtraction when they "intersect completely in either the x- or y-direction." But I prefer to think of it as the alternate formulation offered in the documentation: "In other words, the resul...
Facilities jargon: Energize
Over in the product engineering groups, we aren't often exposed to the jargon employed by our Facilities group. But once in a while, it leaks through and then we get to puzzle it out. Emergency Electrical Outage and Restoral Due to a transformer failure, power to building NNN was shut down from 6:00am to 6:30am on MMMM-DD. Occupants may need to re-energize their office equipment. From what we can gather, re-energize is just a fancy way of saying turn on. Bonus jargon: Restoral.
Entering the world of competitive Ring-Around-the-Rosie
I dreamed that a friend and I were in line at some sort of summer camp to get into the cafeteria. We noticed a glass cabinet with food out in the dining area and asked about it. Turns out that it was available for people to eat, as an alternative to standing in line. We decided to go for it. (Another example of how being lucky is observing what you weren't expecting.) The plates on top of the cabinet were nearly empty, but it never occurred to anybody to open the cabinet door to get the food inside. We opened the door and moved food to the top of the cabinet, as a crowd slowly formed as people noticed, "Hey, lo...
Forcing a file handle closed when it has been opened remotely
Today's Little Program closes a file handle that was opened remotely. It builds on previous discussion on how to use the functions. Forcing a network file handle closed does not actually close the handle. This makes it very different from the various "force handle closed" utilities out there. Rather, forcing a network file handle closed is accomplished by simulating a network failure, so that when the remote machine tries to use the handle again, it's told, "Wha? I'm sorry, we must have a bad connection, because I'm not sure what you're talking about." Since programs which access network resources must dea...
How does InterlockedIncrement work internally?
The Interlocked family of functions perform atomic operations on memory. How do they do it? It depends on the underlying CPU architecture. For some CPUs, it's easy: The x86, for example, has direct support for many interlocked operations by means of the prefix (with the bonus feature that is implied for the opcode.) The ia64 and x64 also have direct support for atomic load-modify-store operations. Most other architectures break the operation into two parts, known as Load-link/store-conditional. The first part (load-link) reads a value from memory and instructions the processor to monitor the memory add...
It rather involved being on the other side of this airtight hatchway: Creating problematic files in a directory that requires administrative access
You have to get there first.
Why does Internet Explorer put tab stops at 8-character intervals instead of 4, like all right-thinking people?
When you embed a TAB character (U+0009) in a <PRE> block (or more precisely, an element whose CSS property is computed to be or ), Internet Explorer will move the current position to the next multiple of eight characters. Many people prefer four. (Some insist that only four is the correct value and anybody who disagrees with them is simply wrong.) Why eight? Because that's what the standard says. All tabs (U+0009) are rendered as a horizontal shift that lines up the start edge of the next glyph with the next tab stop. Tab stops occur at points that are multiples of 8 times the width of a space (U+0020...
Early versions of Aero Peek: Aladdin, Bat Signal, and Squeegee
The feature now known as Aero Peek wasn't born that way. It went through several iterations before becoming what eventually shipped in Windows 7. At the MIX09 conference, Stephan Hoefnagels showed some of the precursors to Aero Peek. Here are the highlights, and the corresponding time codes if you want to jump straight to the demos. Thumbnails in the taskbar (time code 30:20) How it worked: Instead of labeled icons, the taskbar showed miniatures of the windows themselves. How it got its name: Um, it was just named after what it was. Why it failed: When shrunk to taskbar s...
Mom and dad's event-filled first day of school
I dreamed that my wife and I had dropped our daughter off at her new school for the first time, and I made a wrong turn and ended up going the wrong way. We got off at an exit for highway I-5, and the on-ramp turned into a two-lane highway hundreds of feet in the sky. To keep people from going too fast, the road rolled back and forth: First it tilted to the right, then to the left, and so on. (Imagine your hand making the "so-so" gesture.) You just had to drive carefully. The road dead-ended at a building, so we parked the car and got out. It was a tiny gift shop with puppets and marionettes. The attendant came...
Programmatically editing the metadata of an audio file
Today's Little Program edits the metadata of an audio file, ostensibly to correct a spelling error, but really just to show how it's done. Today's smart pointer class library is... (rolls dice)... CComPtr! We open with two helper functions which encapsulate the patterns Get property from property store Call Convert into desired final type Destroy the Set property in property store Create a Call Destroy the Both functions use a lambda to do the type-specific work. Here are some functions that will use the helpers: The function returns an array of po...
How to rescue a broken stack trace on x64: Recovering the stack pointer
No threading, just return addresses.
Why are my posted messages getting lost when the user drags my window around?
This question was inspired by an actual customer question, but I changed a lot of it around to make for a more interesting story. (Trust me, the original story was even more boring.) A customer's background thread posted a message to the main UI thread to signal something (details not important). They found that the posted message was never received if the user was in the process of dragging the main window around at the time the message was posted. Why would dragging a window cause posted messages to be lost? "We used to post a thread message, but then we saw that thread messages are eaten by modal loops, so...
How permanent is the "Remove from this list" action on the Start menu?
From Windows XP to Windows 7, the Start menu showed the programs it thinks you've run most frequently, by employing a conceptually simple but complicated-in-practice algorithm. You can right-click an item on the menu and select Remove from this list. What exactly does this option do? Does it reset the points back to zero, or does it ban the program from the Start menu for all eternity, or something in between? It resets the points back to zero and marks the program as has never been run by the user. This causes it to vanish from the frequently-used list, but if you start running it, it will start ea...
If your product is client-managed, how do you sell the server?
A friend of mine told me about a project he worked on two decades (and three employers) ago. Let's call it Project Nosebleed. Their project used a client-managed database: You have a central file server that houses the database files, which were in a proprietary file format that only the clients understood. All the client applications open the database files, coördinating¹ access among themselves by using file and record locking primitives. All you needed the server for was a place to house the files. It could have been a NAS server for all anybody cared. (Well, except that the concept of NAS hadn't tak...
If you had to deal with preschoolers all day, you'd need a nap too
Today, I'm turning it around: This is a dream that one of my friends had about me! She dreamed that she took her camera to school to take some pictures, possibly for the yearbook. She was somewhat surprised to discover that I was the new preschool teacher. When she popped in to my classroom to get a couple of pictures of me, she wasn't able to take any: Apparently, my new position was so exhausting that I'd had to take a nap on the king-size classroom bed...
What is the official name of the most popular work visa in the United States?
The most popular work visa in the United States is the H1-B visa. But have you looked at its official name? H-1B Specialty Occupations, DOD Cooperative Research and Development Project Workers, and Fashion Models (Today is Labor Day, a holiday in the United States which celebrates the end of summer. Not really, but that's what it has turned into.)
Can an x64 function repurpose parameter home space as general scratch space?
We saw some time ago that the x64 calling convention in Windows reserves space for the register parameters on the stack, in case the called function wants to spill them. But can the called function use the memory for other purposes, too? You sort of already know the answer to this question. Consider this function: How would a naïve compiler generate code for this function? Observe that after spilling the register parameters into their home locations onto the stack, the function modified the local variable, which updated the value in the home location. Since a function can arbitrarily modify a par...
How can I write to a file only as long as nobody's looking?
A customer wanted to know how to detect that the user has opened Notepad to view a particular file. They had come up with method based on polling and sniffing the Notepad title bar, but they found that it consumed a lot of CPU. (They hadn't noticed yet that it doesn't localize, and that it can trigger false positives since Notepad shows only the file name and not the full path in the title bar.) Okay, let's step back and make sure we understand the problem, because this sounds like the sort of thing where the customer is looking for an answer rather than a solution. After all, why Notepad? What about some other ...
The format of data and custom resources
Continuing the highly-sporadic series of Win32 resource formats, today we'll look at the format of resources, which are declared in resource files as . Also the format of custom resources, which are declared in resource files by just giving the custom resource name or ordinal as the second word on the declaration. The format is very simple: It's just raw binary data. If you ask for a 16-bit integer followed by an ANSI string, then you get a 16-bit integer followed by an ANSI string. If you ask for the data to be inserted from a file, then the contents of the file become the resource data. No processing is done...
How can I find out which process and user is modifying a file?
When troubleshooting a problem, you may discover that a file is being modified that shouldn't, and you figure out would be nice if there were some way of finding out which process is modifying the file (so you can get it to stop). Enter the security auditing system. Every securable object has an associated system access control list (SACL) which controls what audit events are raised when a request is made to access the object. You can say, for example, "Log an event in the security event log if somebody tries to open this file for writing but is denied access," or "Log an event in the security event log if some...
The challenge of improvisational historical comedy
I dreamed that one of my friends signed me up for some sort of combination Punk'd/Thank God You're Here improv show without my knowledge, and I had to explain how her husband had unwittingly coined some nonspecific Internet meme.
Why doesn't the "Automatically move pointer to the default button in a dialog box" work for nonstandard dialog boxes, and how do I add it to my own nonstandard dialog boxes?
The Mouse control panel has a setting called Automatically move pointer to the default button in a dialog box, known informally as Snap to default button or simply Snap To. You may have discovered that it doesn't work for all dialog boxes. Why not? The Snap To feature is implemented by the dialog manager. When the window is shown and the setting is enabled, it will center the pointer on the default button. If your application does not use the dialog manager but instead creates its own custom dialog-like windows, then naturally the code in the standard dialog manager will not run. If you want your nonstandard...
If I attach a file to an existing completion port, do I have to close the completion port handle a second time?
There are two ways of calling the function. You can pass a null pointer as the parameter, indicating that you would like to create a brand new completion port, associated with the file handle you passed (if you passed one). Or you can pass the handle of an existing completion port, and the file handle you passed will be associated with that port, in addition to whatever other file handles are already associated with that port. In both cases, the return value on success is a handle to the I/O completion port, either the brand new one or the existing one. The question from a customer was, "In the case where I...
All I/O on a synchronous file handle is serialized; that's why it's called a synchronous file handle
File handles are synchronous by default. If you want asynchronous file handles, you need to pass the flag when you create the handle. And all operations on a synchronous file handle are serialized. You'd think this was a simple and obvious rule, but "Someone" finds it "very surprising that operations can block which only handle file metadata." Imagine if synchronous file handles were not serialized for metadata operations. First of all, it means that the documentation for synchronous file handles suddenly got a lot more complicated. "Some operations on synchronous file handles are serialized, but not others. S...
Adding a confirmation dialog to every drag/drop operation does not solve the problem
A customer wanted to know how to enable a confirmation dialog whenever the user inadvertently perform a drag/drop operation in Explorer to move files within a volume. For example, if I have an S drive mapped to \\server\share, I would like to display the confirmation dialog when users inadvertently drag and drop a file or folder within the S drive. Okay, first of all, the problem statement doesn't match the question. But that's good, because the question was misguided. The question was "How do I add a confirmation dialog to every drag/drop operation?" But the problem statement was "We have users who inadverte...
Microspeak: The train
Hop on board, don't be late, or you'll have to catch the next one.
A dream about forgetting to deploy the backup brake pads
I dreamed that that I was driving through a parking garage when my brakes suddenly failed. I tried executing turns to bleed off speed, but it was largely ineffective. I managed to avoid hitting a parked police car (which had arrived to investigate some other accident), but was unable to avoid another parked car. An insurance adjuster who was on the scene for the first accident looked at my car and discovered that my primary brake pads were completely missing, so the calipers were grabbing air. And in my panic, it never occurred to me to use my left foot to push the button which hot-installs the secondary brake p...
The tiny table sorter – or – you can write LINQ in JavaScript
I had a little side project that displayed status information in a table, and I figured, hey, let me add sorting. And it was a lot easier than I thought. I just put the header row in the and the table contents in the , then I could use this code to sort the table: Each cell can have an optional custom attribute which specifies how the item should sort. If there is no , then I just use the cell's . (My table was constructed at runtime from an , so adding the to the date fields was not difficult.) One handy thing about the functions in the prototype is that as a rule, they do not actually require that the...
If I signal an auto-reset event and there is a thread waiting on it, is it guaranteed that the event will be reset and the waiting thread released before SetEvent returns?
Let's go straight to the question: I have two programs that take turns doing something. Right now, I manage the hand-off with two auto-reset events. In Thread A, after it finishes doing some work, it signals Event B and then immediately waits on Event A. Thread B does the converse: When its wait on Event B completes, it does some work, then signals Event A and then immediately waits on Event B. This works great, but I'm wondering if I can save myself an event and use the same event to hand control back and forth. Is it guaranteed that when Thread A signals Event ...
How do I control the order of the pages in property sheets from my shell extension?
A customer wanted to know whether a shell extension can control the order of the property sheet pages in a property sheet. The interface lets you add pages and replace pages, but nothing about rearranging them. Naturally a shell extension can control the relative order of its own pages (by changing in the order in which it calls ) but how can it affect the order of pages from other shell extensions? Imagine if that were possible. Every shell extension would set itself to be first! The customer was kind enough to explain what they were doing. "We were more concerned about consistency, because our tab appears ...
What's the point of letting you change the GCL_CBCLSEXTRA if it has no effect?
The documentation for the function mentions GCL_CBCLSEXTRA: Sets the size, in bytes, of the extra memory associated with the class. Setting this value does not change the number of extra bytes already allocated. What's the point of letting the application change a value if it has no effect? The class long grants access to the value that was originally passed in the structure when you called , or the Ex-versions mutatus mutandis. The intent is for it to be used with so you can read the value back, in case you forgot, or if you are inspecting somebody else's class (for example, because you wa...
Generally speaking, yanking the power plug unexpectedly should not be part of your business process
A customer had a complex process for setting up their computers, and the process recorded information in the registry so that applications could record their state across reboots. They then noticed that if they yanked the power cord instead of going through the normal Shutdown process, that the registry keys were not reliably updated. They were wondering if there was a function they can call to force the registry to be flushed to disk even if the system doesn't go through a normal shutdown. Patient: "Doctor, it hurts when I do this." Doctor: "Don't do that." You could call the function each time you update th...
Please don't wade across the Strait of Juan de Fuca
I dreamed that I was visiting a scenic location near the Canadian border. A central large body of water had the mainland to the south and east. A river ran southeast, spanned by a footbridge. To the northwest was another land mass, which had gained the nickname "Alaska" even though we were nowhere near Alaska. There was a gift shop on "Alaska", and from there you could either travel further northwest to hike the snowy terrain, or you could take a shuttle train east over the water to the mainland. I had finished a hike on pretend-Alaska and was planning my return. The ringleader of my group was a friend of mine k...
How do I convert a synchronous file handle into an asynchronous one?
Say you opened a file in synchronous mode, and then you realize that you want to issue asynchronous I/O on it, too. One way to do this is to call a second time with the , but this requires you to know the file name, and the file name may not be readily available to the function that wants to do the conversion, or it may not even be valid any longer if the file has been renamed in the meantime. Enter . This basically lets you do a based on another handle rather than a file name. It differs from because it actually goes and opens the file again (as opposed to merely creating another reference to the same file...
Each time I move, my mailbox moves further away
When I was growing up, the mailman letter carrier came right to our front door. The mailbox was mounted on the front of the house right next to the front door. You could check the mail without even getting dressed; just open the door a crack and stick out your hand. Approximate distance from front door to mailbox: less than 1 foot. In the next house I lived in, the mailbox was no longer mounted on the house. Instead, it stood at the end of the driveway. Approximate distance from front door to mailbox: 55 feet. My next house was in a neighborhood which grouped its mailboxes in clusters. The cluster of ...
Why does the CLR report a NullReferenceException even if the referenced access is not exactly the null pointer?
We saw some time ago that before invoking a method on an object, the CLR will generate a instruction to force a null reference exception to be raised if you are trying to invoke a method on a null reference. But why does the CLR raise a if the faulting address is almost but not quite zero? When run, this program raises a rather than an . On the other hand, if you change the address to , then you get the expected . With a little bit of preparation, the CLR optimizes out null pointer checks if it knows that it's going to access the object anyway. For example, if you write then the CLR doesn't need to...
On partially-constructed objects, additional remarks, not as interesting
Don't worry. Our long national nightmare of CLR week is almost over. I had originally planned to write an article about partially-constructed objects, but in the time since I queued up the topic (back in November 2005) to the time I got around to writing it up, I found that Joe Duffy had already written it for me! On partially-constructed objects Read it. Okay, here are some follow-up remarks. One place where people get caught out by partially-constructed objects is when they try to maintain a cache of objects (perhaps with a little bit of action) and stash the objects into the cache before they a...
The mathematical card game Krypto and reaching a level of proficiency where the rules break down
Solving it faster than the rules considered possible.
Weak references have no effect on object lifetime
The class lets you retain a reference to an object while still permitting the object to be garbage collected. When that happens, then the property is and the property is . (Related discussion.) Note, however, that weak references do not alter the decision of the garbage collector whether or not an object is garbage. It merely lets you observe the garbage collector's decision. Some people think that means "Treat this as a regular (strong) reference most of the time, but if there is memory pressure, then you can reclaim the object." This type of reference is called a in Java, but the CLR has no analogous co...
Sometimes sports-rule lawyering comes true: The strikeout with only one thrown pitch
Some time ago, I engaged in some sports-rule lawyering to try to come up with a way the losing team could manage to salvage a win without any remaining at-bats. It involved invoking a lot of obscure rules, but astonishingly one of the rules that I called upon was actually put into effect a few days ago. The Crawfish Boxes provides an entertaining rundown of the sequence of events. Here is the boring version: During his plate appearance, Vinnie Catricala was not pleased with the strike call on the first pitch he received. He exchanged words with the umpire, then stepped out of the batter's box to adjust his e...
The mysterious ways of the params keyword in C#
If a parameter to a C# method is declared with the keyword, then it can match either itself or a comma-separated list of um itselves(?). Consider: This program prints The first call to does not take advantage of the keyword and passes the array explicitly (formally known as normal form). The second call, however, specifies the integers directly as if they were separate parameters. The compiler generates a call to the function in what the language specification calls expanded form. Normally, there is no conflict between these two styles of calling a function with a parameter because only one form act...
A practical reason for shutting down for the Mayan apocalyse
I dreamed that Costco announced that they were closing for the Mayan apocalypse and would reopen two weeks later. Not because they believed in it. Rather, because that was their estimate as to how long it would take people to get through their stockpiles and be ready to go shopping again. Curiously, I had this dream several weeks after the apocalypse date had passed.
Why does BitConverter.LittleEndian return false on my x86 machine?
Welcome to CLR Week 2013, returned from its two-year hiatus. A customer reported that when they checked with the debugger, reported even though they were running on an x86 machine, which is a little-endian architecture. The bytes are extracted in little-endian order, despite the claim that the machine is big-endian. "I don't get it." I didn't know the answer, but I knew how to use a search engine, and a simple search quickly found this explanation: Reading a member from the debugger merely reads the value of the member from memory. That simple statement hides the answer by saying what happens and l...
It rather involved being on the other side of this airtight hatchway: Open access to the application directory
You can't just let anybody into your safety bubble.
The case of the auto-hide taskbar
A customer reported that their taskbar would sometimes spontaneously go into auto-hide mode. What made this particularly insidious was that they had deployed a group policy to prevent users from changing the auto-hide state (because they never wanted the taskbar to auto-hide), so when the taskbar went into auto-hide mode, there was no way to get it out of that mode! The customer's first investigation was to find out where the auto-hide state was recorded. A little bit of registry spelunking (because as far as these people are concerned, everything is in the registry) showed that a single bit in the registry v...
Why does Explorer sometimes show my server name in parentheses?
A customer wanted to know why Explorer showed one of their servers in the folder list the normal way: ⊞ servername but another server showed up "where the server name is parentheses and the node name is in front." ⊞ nodename (servername) "Where is Explorer getting that information, and why are the two servers showing up in different ways?" It's all in the server comment. From the command line, you can view the server comment by typing . For example, You can set the comment with the command line If a server has a comment, then the comment is shown to the user on the expectation tha...
Sometimes people can be so helpless: Finding the owner of a Web page
Internal to Microsoft are thousands of Web sites. This is a story about one of them. On an internal discussion list, somebody asked We just created a new Flurb. Does anyone know how to get listed on http://internalsite/newflurbs? I hadn't heard of that site before, but I checked it out. Neat, it's basically a blog which announces new Flurbs. I can see how somebody would want their Flurb to be listed there. I also saw lots of pieces of information on the page which the person appears not to have noticed. I replied, Um, how about the Email link in the navigation bar? Or did you try that and it didn't work? ...
I'm sure that Star Trek-themed parties exist, so why has no one ever scheduled one as a Microsoft holiday party?
I dreamed that I was attending a Star Trek-themed company party. Nobody was dressed as a Starfleet officer or anything exotic. Half of the people ignored the party theme and came in cocktail attire, and half were dressed in Renaissance or Elizabethan clothes, but they represented Star Trek aliens because they were not all white Europeans, and some of them had funny hair. And because we were told that it was a Star Trek-themed party, and in dreams you don't question this sort of thing. I recognized some of the aliens as staff members from the previous Star Trek-themed party and concluded that most of the aliens w...
A program for my nieces: The ABCs, part 4
Disabling autorepeat in my ABC program was largely sufficient to keep my nieces happy, given their instructions to press only one key at a time. Once in a while, though, they would hit the context menu key in the bottom right corner of the keyboard, and then they'd get stuck because they didn't know how to dismiss it. So let's disable that key outright. Well, that was awfully anticlimactic, wasn't it.
From Microsoft’s mail room to the board room
I think it was a Chevy.
What is the default cursor for a thread?
When we looked at the process by which the cursor is set, we neglected to discuss the case where nobody bothers to set the cursor. What is the ultimate default cursor? Let's write a program that refuses to set the cursor. Take the scratch program and add these lines: What we did was make the window explicitly refuse to set the cursor by making it do nothing and return , which means, "It's all good. I set the cursor!" (Liar, liar, pants on fire.) Run this program, move the cursor over the window, and what do you get? The hourglass. Now, this is clearly some sort of pathological case, where there is a...
Nighttime pictures of London and Tokyo
Some eye candy for you: Stunning pictures of London from above at night, more of London from above at night. Tokyo at night, though from ground level, one of a series of photo walks.
Windows 7 no longer tries to guess application size and other information
Back in the old days, if an application did not provide information like its Estimated Size or Install Date, then the Add/Remove Programs control panel tried to guess the values by searching your hard drives for files and directories that bore a superficial resemblance to the application. (Note that I use the word drives in the plural. It actually searched all of your drives, because some applications may have been installed to secondary drives. I can imagine the bug report that led to this extended search. "I installed LitWare 2000 to my D: drive, and the Add/Remove Programs control panel shows no information f...
Office Office Office Malkovich Office Office Office
Some years ago, a colleague of mine received a message from our IT department. It began like this: You are receiving this notification because our records show that the machines below are still running a pre-release version of Office 2010. All pre-release versions of Office 2010 will expire on Office 31, 2010. Either the Office team managed to name a month after themselves, or the IT department had a bit too much Office on their mind.
At least it's clear who will NOT be bunking together
I dreamed that I was on a business trip with two colleagues. We discussed Canadian science broadcaster David Suzuki and how in photos of him as a teenager, he looked like Elvis Presley. (Note: Not actually true as far as I know. Remember, this is a dream.) Fortunately, the hotel room we booked had three beds. But if Michael Jackson hadn't canceled, then two of us would have had to double-up, and we briefly discussed who would be bunking together. Possibly my two colleagues together, or me with the first colleague, or me with the second colleague. It went without saying, however, that had Michael Jackson actuall...
A program for my nieces: The ABCs, part 3
One problem I discovered when my nieces ran my initial ABC program was that they had a habit of holding down a key, thereby triggering autorepeat. I had instructed them not to mash the keyboard but rather to press only one key at a time, and while they were good at adhering to the "one key at a time" rule, they also interpreted it as "type really slowly" and ended up autorepeating a lot. So let's disable keyboard autorepeat. Of course, one way to do this would be to change the system keyboard autorepeat setting, but that would be using global state to manage a local problem. Instead, we just filter the aut...