Coder's Guild Mailing List

Re: Changing resolutions in C/C++

Posted by Alisdair Owens on 2001-05-01

Below is some code i dug out from one of my old delphi projects.  It should not 
be too hard to adapt, as it is made largely of API calls (this assumes you are 
working with windows).  It first queries the registry to find the current 
resolution, and saves this in a tdevicemode variable.  It then retrieves all the 
possible bits per pixel/resolution settings, in this case trying to find to 
800x600, 16bpp.  It uses EnumDisplaySettings to do this.  It then uses 
ChangeDisplaySettings to change the resolution.

ChangeDisplaySettings uses the following syntax:

Changedisplaysettings(lpDevMode:PDevicemode;dwFlags:DWORD):Longint

it returns  the following values:

Change successful:DISP_CHANGE_SUCCESSFUL
Computer needs to be restarted for change:DISP_CHANGE_RESTART
Invalid flags passed:DISP_CHANGE_BADFLAGS
Change failed:DISP_CHANGE_FAILED
Tried to set invalid mode:DISP_CHANGE_BADMODE

DwFlags can take the following values:
0 :The change will be made dynamically(when restarted, computer will return to 
old resolution)
CDS_UPDATEREGISTRY :Change is made, and the registry is updated (Resolution will 
be set until the user sets it back)
CDS_TEST :The change is not made but the system is tested to see if it could be 
made.



Code:

// finds old resolution from registry and
// sorts out into integer variables
// of horz and vert resolution
var
olddmode,DevMode2:tdevicemode;
devmode:TDevmode;
begin
if not application.terminated then begin
reg := tregistry.create;
reg.RootKey := HKEY_CURRENT_CONFIG;
reg.OpenKey('display',false);
reg.openkey('settings',false);
bpp := reg.Readstring('BitsPerPixel');
res := reg.ReadString('Resolution');
bits := strtoint(bpp);
hres := strtoint(copy(res,0,pos(',',res)-1));
vres := strtoint(copy(res,pos(',',res) + 1,length(res) - pos(',',res)));
reg.free;
found := false;
while (EnumDisplaySettings(nil,i,DevMode)) do begin
      with Devmode do begin
           if (dmpelswidth = hres) and (dmpelsheight = vres) and (dmbitsperpel = 
bits) then EnumDisplaySettings(nil,i,olddmode); // saves old resolution and 
colour depth

// This attempts to change resolution and colour depth and stops play if it is 
unable to do so.
           if (dmpelswidth = 800) and (dmpelsheight = 600) and (dmbitsperpel = 
16) then begin
           if EnumDisplaySettings(nil,i,Devmode2) then begin
           success := ChangeDisplaySettings(DevMode2, 0);
           found := true;
           end;
      end;
      end;
inc(i);
end;


Hope this helps,

Alisdair Owens