Guarding against system changes between function calls in Windows

41 views Asked by At

Given some code like this...

auto res = GetScreenResolution();

// Can windows change the screen resolution between these calls? 
// How do you guard against it?

DoSomething(res);

Can the resolution of the screen be changed between the function calls? Say from the user adjusting display settings. I assume it can but I'll ask for certainty.

If the resolution is changed between calls, then the function DoSomething might not work correctly, or cause a major problem depending on the code.

Is there any way at all of making sure the system (or particular settings) cannot be changed during the execution of a piece of code?

The same concept could be applied to various things, like checking if a network is up or checking the status of a file.

The probability of something happening is so small that it's not worth bothering with, but I was curious.

Some overnight thoughts...

  1. Call GetScreenResolution() again after DoSomething() to check for a match. This would also allow you to undo changes you've made and correct them. It's still possible for a problem to occur, but it's much much lower still.

  2. With exceptions, DoSomething() may throw a software exception with out of date data. You can then do whatever is necessary.

  3. If you have to do a lot of processing between GetScreenResolution and DoSomething, say for a minute, then it may be worth checking for changes to the system. If you receive a message that resolution changed, you can also reset the processing if you're architecture allows for that.

1

There are 1 answers

1
Anders On BEST ANSWER

You just have to prepare for failure and/or make sure you are notified about any changes.

Even if there was a lock you could take to prevent another application from changing the display settings there is nothing you can do to prevent me from pulling out my monitor cable and Windows reacting to that and making my laptop screen the primary monitor.

If you look at ChangeDisplaySettings for example you will see this on MSDN:

When the display mode is changed dynamically, the WM_DISPLAYCHANGE message is sent to all running applications with the following message parameters.

The only thing you can do to prevent something is to use a job object to restrict a specific process/processes under your control from calling certain functions (JOB_OBJECT_UILIMIT_DISPLAYSETTINGS etc.).