How to programmatically change the resolution of a specific monitor?

风格不统一 提交于 2020-01-04 05:11:06

问题


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


回答1:


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;


来源:https://stackoverflow.com/questions/15101977/how-to-programmatically-change-the-resolution-of-a-specific-monitor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!