goggle pink
goggle pink

Reputation: 132

How to programmatically change the resolution of a specific monitor?

How do you programmatically change the resolution of a specific monitor? For instance can the secondary monitor resolution be programmatically changed?

Upvotes: 3

Views: 4729

Answers (1)

TLama
TLama

Reputation: 76693

The following function might be your starting point. It tries to change the resolution of a display device with index specified by the Index parameter (if exists such) to a width and height (in pixels) given by the Width, Height parameters. The function returns True, if the display device with given index is found and the resolution of it has been successfully changed, False otherwise.

You haven't specified whether you want to change the resolution permanently (if you want to store the setting changes), or change it only temporarily. The following example does it temporarily, but you can quite simply change this behavior if you use in the second ChangeDisplaySettingsEx function call the CDS_UPDATEREGISTRY value for the dwflags parameter:

function ChangeMonitorResolution(Index, Width, Height: DWORD): Boolean;
var
  DeviceMode: TDeviceMode;
  DisplayDevice: TDisplayDevice;
begin
  Result := False;
  ZeroMemory(@DisplayDevice, SizeOf(DisplayDevice));
  DisplayDevice.cb := SizeOf(TDisplayDevice);
  // get the name of a device by the given index
  if EnumDisplayDevices(nil, Index, DisplayDevice, 0) then
  begin
    ZeroMemory(@DeviceMode, SizeOf(DeviceMode));
    DeviceMode.dmSize := SizeOf(TDeviceMode);
    DeviceMode.dmPelsWidth := Width;
    DeviceMode.dmPelsHeight := Height;
    DeviceMode.dmFields := DM_PELSWIDTH or DM_PELSHEIGHT;
    // check if it's possible to set a given resolution; if so, then...
    if (ChangeDisplaySettingsEx(PChar(@DisplayDevice.DeviceName[0]), 
      DeviceMode, 0, CDS_TEST, nil) = DISP_CHANGE_SUCCESSFUL)
    then
      // change the resolution temporarily (if you use CDS_UPDATEREGISTRY
      // value for the penultimate parameter, the graphics mode will also
      // be saved to the registry under the user's profile; for more info
      // see the ChangeDisplaySettingsEx reference, dwflags parameter)
      Result := ChangeDisplaySettingsEx(PChar(@DisplayDevice.DeviceName[0]),
        DeviceMode, 0, 0, nil) = DISP_CHANGE_SUCCESSFUL;
  end;
end;

An example how to change resolution of a secondary display device (device with index 1) to 800x600:

procedure TForm1.Button1Click(Sender: TObject);
begin
  if ChangeMonitorResolution(1, 800, 600) then
    ShowMessage('Resolution of display device with index 1 has been changed!')
  else
    ShowMessage('Display device with index 1 doesn''t exist, doesn''t support ' +
      'resolution 800x600 or changing failed due to a reason, which you might ' +
      'know if the author of this function wouldn''t be so lazy!');
end;

Upvotes: 5

Related Questions