Advertisement
aveyo

CS2_launcher

Feb 19th, 2024 (edited)
4,039
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 46.10 KB | Gaming | 0 0
  1. @(set ^ "0=%~f0" -d ') & start "cmd" powershell -nop -c . ([scriptblock]::Create((gc $env:0)-join[char]13)) & exit /b ')
  2. <#
  3.   Counter-Strike 2 launcher - AveYo, 2024.05.30
  4.   sets screen resolution before starting the game, to alleviate input lag, alt-tab & windows on secondary screens issues
  5.   when res matches, both Desktop-friendly and Exclusive Fullscreen have low input lag and fast alt-tab / win-tab
  6.   once the game is closed, restores the resolution to previous one, or max if using option further below
  7.   + automatically fallback to max available if the chosen res is not yet defined or invalid
  8.   + proper handling of multiple screens, game starts on $force_screen or current screen even if not set as primary
  9.   + clears steam verify game integrity after a crash to relaunch quicker, hopefully preventing a timeout; toggles fso
  10.   + alleviates missing settings under connection problems / cloud conflicts / roaming profiles via cloud.cfg
  11.   + overrides video settings not present in ui to set lower than low quality with competitive shadows still visible - RIP
  12. #>
  13.  
  14. #:: override resolution, no: -1 max: 0 |  if not appearing in res list, create the custom res in gpu driver settings / cru
  15. #:: best custom res for [4:3] = 1024x768  1088x816  1280x960  1440x1080 ; [16:9] = 1366x768  1456x816  1632x918  1920x1080
  16. $force_width     = -1
  17. $force_height    = -1
  18. $force_refresh   = -1
  19.  
  20. #:: override video settings with the preset below: yes 1; no -1 or 0  
  21. $force_settings  =  1
  22.  
  23. #:: override specific video settings - prefix with # lines to remain unchanged (adjust those in-game and relaunch)
  24. #:: after 23.05 patch RIP the last vestige of cfg tweaking so no point in hard-coding anymore - shame on valve devs!
  25. $video = @{                                                           #        Shadow of a Potato preset RIP    more jpeg:
  26. # "setting.mat_vsync"                                = "0"            #  0
  27. # "setting.msaa_samples"                             = "2"            #  2     enable AA when using FSR              0
  28. # "setting.r_csgo_cmaa_enable"                       = "0"            #  0     use msaa 2 instead                    1
  29. # "setting.videocfg_shadow_quality"                  = "2"            #  2     RIP, only shadows high usable         0
  30. # "setting.videocfg_texture_detail"                  = "0"            #  0     texture high: 2 | med: 1 | low: 0
  31. # "setting.r_texturefilteringquality"                = "3"            #  3     anyso16x: 5 | trilinear: 1            0
  32. # "setting.shaderquality"                            = "0"            #  0     smooth shadows: 1 | fps: 0
  33. # "setting.videocfg_particle_detail"                 = "0"            #  0
  34. # "setting.videocfg_ao_detail"                       = "0"            #  0
  35. # "setting.videocfg_hdr_detail"                      = "-1"           #  -1    HDR auto: -1 | performance (8bit): 3
  36. # "setting.videocfg_fsr_detail"                      = "2"            #  0     FSR scales down the viewport, keeping ui res
  37.                                                                       #        quality: 2 balanced: 3 performance: 4
  38. # "setting.r_low_latency"                            = "1"            #  1
  39. }
  40. $machine = @{
  41. # "r_player_visibility_mode"                         = "0"            #  0     not in cs2_video.txt
  42. # "r_fullscreen_gamma"                               = "2.2"          #  2.2   not in cs2_video.txt
  43. }
  44. $extra_launch_options = '-favor_consistent_framerate '                #        my placebo is smoother than yours
  45. #$extra_launch_options+= '-high -threads 7 -console '                 #  uncomment if rock-stable and 6 or more cpu threads
  46.  
  47. #:: gather freshest keys / user / machine .vcfg into cloud.cfg for applying settings when offline: 1  no: 0
  48. $cloud_cfg       =  1
  49.  
  50. #:: override fullscreen mode, exclusive: 1 desktop-friendly: 0
  51. $force_exclusive =  1
  52.  
  53. #:: override fullscreen optimizations (FSO), enable: 1 disable: 0
  54. $enable_fso      =  0
  55.  
  56. #:: override screen or use current -1 | this is 1st number in the screen list; second number is for -sdl_displayindex
  57. $force_screen    = -1
  58.  
  59. #:: override script handling or use default 0
  60. $do_not_set_desktop_res_to_match_game = 0
  61. $do_not_restore_res_use_max_available = 0
  62. $do_not_hide_script_window_on_waiting = 0
  63.  
  64. # main script section ---------------------------------------------------------------------- switch syntax highlight to powershell
  65. $APPID    = 730
  66. $APPNAME  = "cs2"
  67. $GAMENAME = "Counter-Strike Global Offensive"
  68. $GAMEMOD  = "csgo"
  69. $GAMEBIN  = "bin\win64"
  70. $M_CONFIG = "${APPNAME}_machine_convars.vcfg"
  71. $U_CONFIG = "${APPNAME}_user_convars_0_slot0.vcfg"
  72. $K_CONFIG = "${APPNAME}_user_keys_0_slot0.vcfg"
  73. $V_CONFIG = "${APPNAME}_video.txt"
  74.  
  75. # check if already opened
  76. sp HKCU:\Console\cmd ScreenColors 0x0b -type dword -ea 0; sp HKCU:\Console\cmd QuickEdit 0 -type dword -ea 0
  77. ps | where {$_.MainWindowTitle -eq "$APPNAME launcher"} | kill; $host.ui.RawUI.WindowTitle = "$APPNAME launcher"
  78. if (ps $APPNAME -ea 0) { write-host " $APPNAME is running " -fore Black -back Yellow; sleep 3; exit 0 }
  79.  
  80. # detect STEAM and specific APP
  81. $STEAM = resolve-path (gpv "HKCU:\SOFTWARE\Valve\Steam" SteamPath)
  82. gc "$STEAM\steamapps\libraryfolders.vdf" |foreach  {$_ -split '"',5} |where {$_ -like '*:\\*'} |foreach {
  83.   $lib = resolve-path "$_\steamapps" ; $GAMEROOT = "$lib\common\$GAMENAME\game"; if (test-path "$GAMEROOT\$GAMEMOD\steam.inf") {
  84.     $STEAMAPPS = "$lib"; $GAMEDIR = "$GAMEROOT\$GAMEMOD"; $LAUNCHER = "$GAMEROOT\$GAMEBIN\$APPNAME.exe"
  85. }}
  86.  
  87. #:: detect per-user data path
  88. pushd "$STEAM\userdata"
  89. $USRCLOUD = split-path (dir "localconfig.vdf" -File -Recurse | sort LastWriteTime -Descending | Select -First 1).DirectoryName
  90. $USRLOCAL = "$USRCLOUD\$APPID\local"
  91. popd
  92.  
  93. # detect roaming profile path
  94. if ($env:USRLOCALCSGO -and (test-path "$env:USRLOCALCSGO\cfg\$M_CONFIG")) { $USRLOCAL = "$env:USRLOCALCSGO" }
  95.  
  96. #:: use freshest config across supported locations
  97. if ($cloud_cfg -gt 0) {
  98.   robocopy "$GAMEDIR\cfg/" "$USRLOCAL\cfg/" $M_CONFIG $U_CONFIG $K_CONFIG $V_CONFIG /XO >''
  99.   robocopy "$USRCLOUD\$APPID\local\cfg/" "$USRLOCAL\cfg/" $M_CONFIG $U_CONFIG $K_CONFIG $V_CONFIG /XO >''
  100.   robocopy "$env:USRLOCALCSGO\cfg/" "$USRLOCAL\cfg/" $M_CONFIG $U_CONFIG $K_CONFIG $V_CONFIG /XO >''
  101. }
  102.  
  103. #:: export steam userdata configs to cfg\cloud.cfg - then can exec cloud to restore missing settings
  104. if ($cloud_cfg -gt 0) {
  105.   sc "$GAMEDIR\cfg\cloud.cfg" "// steam cloud settings from $K_CONFIG & $U_CONFIG & $M_CONFIG`r`n" -force -ea 0
  106.   $keys_vcfg = "$USRLOCAL\cfg\$K_CONFIG"; $cfg = new-object System.Text.StringBuilder
  107.   if (test-path $keys_vcfg) {
  108.     gc $keys_vcfg |foreach { $l = $_ -split '"'; if ($l.count -eq 5) { # -and $l[3] -ne '<unbound>'
  109.       $cfg.Append('bind "')>''; $cfg.Append($l[1])>''; $cfg.Append('" "')>''; $cfg.Append($l[3])>''
  110.     $cfg.AppendLine('" | grep %%')>'' } }
  111.     if ($cfg.length -gt 0) { ac -Literal "$GAMEDIR\cfg\cloud.cfg" -Value $cfg.ToString() }
  112.   }
  113.   $user_vcfg = "$USRLOCAL\cfg\$U_CONFIG"; $cfg = new-object System.Text.StringBuilder
  114.   if (test-path $user_vcfg) {
  115.     gc $user_vcfg |foreach { $l = $_ -split '"'; if ($l.count -eq 5) {
  116.       $cfg.Append($l[1])>''; $cfg.Append(' "')>''; $cfg.Append($l[3])>''; $cfg.AppendLine('"')>'' } }
  117.     if ($cfg.length -gt 0) { ac -Literal "$GAMEDIR\cfg\cloud.cfg" -Value $cfg.ToString() }
  118.   }
  119.   $machine_vcfg = "$USRLOCAL\cfg\$M_CONFIG"; $cfg = new-object System.Text.StringBuilder
  120.   if (test-path $machine_vcfg) {
  121.     gc $machine_vcfg |foreach { $l = $_ -split '"'; if ($l.count -eq 5) {
  122.       $cfg.Append($l[1].Split('$')[0])>''; $cfg.Append(' "')>''; $cfg.Append($l[3])>''; $cfg.AppendLine('"')>'' } }
  123.     if ($cfg.length -gt 0) { ac -Literal "$GAMEDIR\cfg\cloud.cfg" -Value $cfg.ToString() }
  124.   }
  125.   ac -Literal "$GAMEDIR\cfg\cloud.cfg" -Value "execifexists autoexec.cfg";
  126. }
  127.  
  128. #:: generate a blank autoexec.cfg if not already found
  129. if (-not (test-path "$GAMEDIR\cfg\autoexec.cfg")) { sc "$GAMEDIR\cfg\autoexec.cfg" "" }
  130.  
  131. #:: clear verify integrity flags after a crash for quicker relaunch
  132. $appmanifest="$STEAMAPPS\appmanifest_$APPID.acf"
  133. if (test-path $appmanifest) {
  134.   $ACF = [io.file]::ReadAllText($appmanifest)
  135.   if ($ACF -match '"FullValidateAfterNextUpdate"\s+"1"' -or $ACF -notmatch '"StateFlags"\s+"4"') {
  136.     " update or verify integrity flags detected, will clear them and restart Steam...`n"
  137.     'dota2','cs2','steamwebhelper','steam' |foreach {kill -name $_ -force -ea 0} ; sleep 3; del "$STEAM\.crash" -force -ea 0
  138.     $ACF = $ACF -replace '("FullValidateAfterNextUpdate"\s+)("\d+")',"`$1`"0`"" -replace '("StateFlags"\s+)("\d+")',"`$1`"4`""
  139.     [io.file]::WriteAllText($appmanifest, $ACF)
  140.   }
  141. } else {
  142.   sc $appmanifest @"
  143. "AppState"
  144. {
  145.   "AppID"  "$APPID"
  146.   "Universe" "1"
  147.   "installdir" "$GAMENAME"
  148.   "StateFlags" "4"
  149. }
  150. "@ -force; " $appmanifest missing or wrong lib path detected! continuing with a default manifest...`n";
  151. }
  152.  
  153. #:: toggle fullscreen optimizations for game launcher - FSO as a concept is an abomination - ofc it causes input lag
  154. $flags = 'HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers'
  155. $found = (gi $flags -ea Ignore).Property -contains $LAUNCHER
  156. $valid = $found -and (gpv $flags $LAUNCHER) -like '*DISABLEDXMAXIMIZEDWINDOWEDMODE*'
  157. if ($enable_fso -eq 0 -and (!$found -or !$valid)) {
  158.   " disabling per app os fullscreen (un)optimizations"
  159.   ni $flags -ea 0; sp $flags $LAUNCHER '~ DISABLEDXMAXIMIZEDWINDOWEDMODE HIGHDPIAWARE' -force -ea 0
  160. }
  161. if ($enable_fso -eq 1 -and $valid) {rp $flags $LAUNCHER -force -ea 0}
  162.  
  163. #:: warn if steam not already running
  164. if ($null -eq (get-process 'steam' -ea 0)) { " steam not running, will take a bit longer...`n" }
  165.  
  166. #:: parse game launch options
  167. $lo = (gc "$USRCLOUD\config\localconfig.vdf") -join "`n"
  168. $lo = (($lo -split '\n\s{5}"' + $APPID + '"\n\s{5}{\n')[1] -split '\n\s{5}}\n')[0]
  169. $lo = (($lo -split '\n\s{6}"LaunchOptions"\s+"')[1] -split '"\n')[0]
  170. $launcher_width = -1; $launcher_height = -1; $launcher_refresh = -1; $launcher_exclusive = -1; $launcher_screen = -1
  171. if ($lo -match '-w(idth)?\s+(\d+)')         { $launcher_width     = [int]$matches[2] }
  172. if ($lo -match '-h(eight)?\s+(\d+)')        { $launcher_height    = [int]$matches[2] }
  173. if ($lo -match '-r(efresh)?\s+([\d.]+)')    { $launcher_refresh   = [decimal]$matches[2] }
  174. if ($lo -match '-fullscreen\s+')            { $launcher_exclusive = 1 }
  175. if ($lo -match '-sdl_displayindex\s+(\d+)') { $launcher_screen    = [int]$matches[1] }
  176.  
  177. #:: parse video txt file
  178. $video_config = "$USRLOCAL\cfg\$V_CONFIG"
  179. $cfg_width = -1; $cfg_height = -1; $cfg_refresh = -1; $cfg_numer = -1; $cfg_denom = -1; $cfg_exclusive = -1
  180. if (test-path $video_config) {
  181.   $lines = (gc $video_config); $txt = $lines -join "`n"
  182.   if ($txt -match '"setting.defaultres"\s+"([^"]*)"')              { $cfg_width     = [int]$matches[1] }
  183.   if ($txt -match '"setting.defaultresheight"\s+"([^"]*)"')        { $cfg_height    = [int]$matches[1] }
  184.   if ($txt -match '"setting.refreshrate_numerator"\s+"([^"]*)"')   { $cfg_numer     = [int]$matches[1] }
  185.   if ($txt -match '"setting.refreshrate_denominator"\s+"([^"]*)"') { $cfg_denom     = [int]$matches[1] }
  186.   if ($txt -match '"setting.fullscreen"\s+"([^"]*)"')              { $cfg_exclusive = [int]$matches[1] }
  187.   #:: compute numerator / denominator = refresh for video txt file
  188.   if ($cfg_numer -gt 0 -and $cfg_denom -gt 0) { $cfg_refresh = [decimal]$cfg_numer / $cfg_denom } else { $cfg_refresh = 0 }
  189. }
  190.  
  191. #:: decide which sets of video options overrides to use: script has priority, then launch options, then cfg
  192. $width   = (0,$cfg_width)[$cfg_width -gt 0];   $height = (0,$cfg_height)[$cfg_height -gt 0]
  193. $refresh = 0;  $exclusive = $cfg_exclusive
  194. if ($launcher_width -ge 0)     {$width = $launcher_width}         ; if ($force_width -ge 0)     {$width = $force_width}
  195. if ($launcher_height -ge 0)    {$height = $launcher_height}       ; if ($force_height -ge 0)    {$height = $force_height}
  196. if ($launcher_refresh -ge 0)   {$refresh = $launcher_refresh}     ; if ($force_refresh -ge 0)   {$refresh = $force_refresh}
  197. if ($launcher_exclusive -ge 0) {$exclusive = $launcher_exclusive} ; if ($force_exclusive -ge 0) {$exclusive = $force_exclusive}
  198. if ($launcher_screen -ge 0)    {$screen_sdr = $launcher_screen}   ; if ($force_screen -ge 0)    {$screen = $force_screen}
  199. if ($refresh -gt 0) {
  200.   $hz = ([string]$refresh).Split('.'); $denom = 1000
  201.   if ($hz.length -eq 2) { $numer = [int]($hz[0] + $hz[1].PadRight(3,'0')) } else { $numer = [int]($hz[0] + "000") }
  202. }
  203.  
  204. #::  many thanks to /u/wazernet for testing and suggestions
  205. $mode = "$width x $height ${refresh}Hz " + ('Desktop-friendly','Exclusive')[$exclusive -gt 0] + (' + FSO','')[$enable_fso -eq 0]
  206. " {0,-13} = {1}" -f "launcher exe", "$LAUNCHER"
  207. " {0,-13} = {1}" -f "autoexec.cfg", "$GAMEDIR\cfg\"
  208. " {0,-13} = {1}" -f "$V_CONFIG",    "$USRLOCAL\cfg\"
  209. " {0,-13} = {1}" -f "display mode", "$mode `n"
  210.  
  211. #:: set screen resolution via SetRes before launching the game, to alleviate input lag, alt-tab and secondary screens issues
  212. $library1 = "SetRes"; $version1 = "2024.3.10.0"; $about1 = "set screen resolution"; $path1 = "$env:APPDATA\AveYo\$library1.dll"
  213. <# usage:
  214.   [SetRes.Displays]::Change(output=[0:none 1:def], screen, width, height, refresh=[0:def], test=[0:change 1:test])
  215.   [SetRes.Displays]::List(output=[0:none 1:filter 2:all], screen, minw=[1024], maxw=[16384], maxh=[16384])
  216.   returns array of: sdl_idx, screen, current_width, current_height, current_refresh, max_width, max_height, max_refresh
  217.   the c# typefinition at the end of the script gets pre-compiled rather than let powershell do it slowly every launch #>
  218. if ((gi $path1 -force -ea 0).VersionInfo.FileVersion -ne $version1) { del $path1 -force -ea 0 } ; if (-not (test-path $path1)) {
  219.   mkdir "$env:APPDATA\AveYo" -ea 0 >'' 2>''; pushd $env:APPDATA\AveYo; " one-time initialization of $library1 library..."
  220.   [io.file]::WriteAllText("$env:APPDATA\AveYo\$library1.cs", ([io.file]::ReadAllText($env:0) -split '<#[:]LIBRARY1[:].*')[1])
  221.   $csc = join-path $([Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) 'csc.exe'
  222.   start $csc -args "/out:$library1.dll /target:library /platform:anycpu /optimize /nologo $library1.cs" -nonew -wait; popd
  223. }
  224. Import-Module $path1
  225. $display = [SetRes.Displays]::Init($screen)
  226. $sdl_idx = $display[0];  $screen = $display[1];  $primary = $display[2] -gt 0;  $multimon = $display[3] -gt 1
  227.  
  228. #:: restore previous resolution if game was not gracefully closed last time
  229. if ($do_not_set_desktop_res_to_match_game -le 0 -and (test-path "$GAMEDIR\cfg\SetRes.cfg")) {
  230.   $restore = (gc "$GAMEDIR\cfg\SetRes.cfg") -split ','
  231.   if ($null -eq (get-process $APPNAME -ea 0)) {
  232.     $c = [SetRes.Displays]::Change(0, $restore[1], $restore[2], $restore[3], $restore[4])
  233.   }
  234. }
  235.  
  236. #:: SetRes automatically picks a usable mode if the change is invalid so result might differ from the request
  237. $oldres  = [SetRes.Displays]::List(1, $screen)
  238. if ($width   -le 0) { $width  = $oldres[2] }
  239. if ($height  -le 0) { $height = $oldres[3] }
  240. if ($refresh -le 0) { $max_refresh = [SetRes.Displays]::List(0, $screen, $width, $width, $height); $refresh = $max_refresh[7] }
  241. $newres  = [SetRes.Displays]::Change(1, $screen, $width, $height, $refresh, 1)
  242. $width   = $newres[5]; $restore_width   = $newres[2]
  243. $height  = $newres[6]; $restore_height  = $newres[3]
  244. $refresh = $newres[7]; $restore_refresh = $newres[4]
  245. function max {$r = [SetRes.Displays]::Change(1, $oldres[1], $oldres[5], $oldres[6], $oldres[7])} # console command to set max res
  246. function min {$r = [SetRes.Displays]::Change(1, $oldres[1], 1024,       768,        $oldres[7])} # console command to set min res
  247. if ($do_not_restore_res_use_max_available -ge 1) {
  248.   $restore_width = $oldres[5]; $restore_height = $oldres[6]; $restore_refresh = $oldres[7]
  249. }
  250. $sameres = $width -eq $restore_width -and $height -eq $restore_height -and $refresh -eq $restore_refresh
  251. $ratio   = $width / $height
  252. if ($ratio -le 4/3) {$ar = 0} elseif ($ratio -le 16/10) {$ar = 2} elseif ($ratio -le 16/8.9) {$ar = 1} else {$ar = 3}
  253.  
  254. #:: update video overrides in case the initial mode was invalid and SetRes applied a fallback
  255. if ($force_settings -le 0) { $video = @{} }
  256. $video["setting.defaultres"]                   = $width
  257. $video["setting.defaultresheight"]             = $height
  258. $video["setting.refreshrate_numerator"]        = $refresh
  259. $video["setting.refreshrate_denominator"]      = 1
  260. $video["setting.fullscreen"]                   = (0,1)[$exclusive -eq 1]
  261. $video["setting.coop_fullscreen"]              = (0,1)[$exclusive -ne 1]
  262. $video["setting.nowindowborder"]               = 0
  263. $video["setting.fullscreen_min_on_focus_loss"] = 0
  264. $video["setting.aspectratiomode"]              = $ar
  265.  
  266. #:: update cfg files with the overrides
  267. $video_config = "$USRLOCAL\cfg\$V_CONFIG"
  268. if (-not (test-path $video_config)) {sc $video_config "`"video.cfg`"`n{`n`t`"Version`"`t`t`"12`"`n}`n" -force -ea 0 }
  269. if ((test-path $video_config) -and $force_settings -ge 1) {
  270.   $lines = (gc $video_config); $txt = $lines -join "`n"; $cfg = new-object System.Text.StringBuilder # dos line-endings
  271.   foreach ($k in $video.Keys) {
  272.     if ($k -like 'setting.*' -and $txt -notmatch "`"$k`"") { $cfg.Append("`r`n`t`"$k`"`t`t`"$($video.$k)`"")>'' }
  273.   }
  274.   if ($cfg.length -gt 0) { -1..-10 |foreach { if ($lines[$_] -match "^}$") { $lines[$_ - 1] += $cfg.ToString(); return } } }
  275.   if ($cfg.length -gt 0) {sc $video_config $lines -force -ea 0 }
  276.   (gc $video_config) |foreach {
  277.     foreach ($k in $video.Keys) { if ($_ -like "*$k`"*") {
  278.       $_ = $_ -replace "(`"$k`"\s+)(`"[^`"]*`")","`$1`"$($video.$k)`"" } }; $_ } | sc $video_config -force -ea 0
  279. }
  280. $machine_config = "$USRLOCAL\cfg\$M_CONFIG"
  281. if (-not (test-path $machine_config)) {sc $machine_config "`"config`"`n{`n`t`"convars`"`n`t{`n`t`t`n`t}`n}`n" -force -ea 0 }
  282. if ((test-path $machine_config) -and $force_settings -ge 1) {
  283.   $lines = (gc $machine_config); $txt = $lines -join "`n"; $cfg = new-object System.Text.StringBuilder # unix line-endings
  284.   foreach ($k in $machine.Keys) { if ($txt -notmatch "`"$k`"") { $cfg.Append("`n`t`t`"$k`"`t`t`"$($machine.$k)`"")>'' } }
  285.   if ($cfg.length -gt 0) { -1..-10 |foreach { if ($lines[$_] -match "^\s}$") { $lines[$_ - 1] += $cfg.ToString(); return } } }
  286.   if ($cfg.length -gt 0) { sc $machine_config (($lines -join "`n") + "`n") -noNewLine -force -ea 0 }
  287.   (gc $machine_config) |foreach {
  288.     foreach ($k in $machine.Keys) { if ($_ -like "*$k`"*") {
  289.       $_ = $_ -replace "(`"$k`"\s+)(`"[^`"]*`")","`$1`"$($machine.$k)`"" } }; $_ } | sc $machine_config -force -ea 0
  290. }
  291.  
  292. #:: prepare video launch options
  293. $window = @("-force_allow_coop_fullscreen -coop_fullscreen", "-force_allow_excl_fullscreen -fullscreen")[$exclusive -ge 1]
  294. $video_options = "$window -width $width -height $height -refresh $refresh -sdl_displayindex $sdl_idx"
  295. " options  = $video_options"
  296. #pause
  297.  
  298. #:: prepare steam quick options
  299. $quick = '-quicklogin -skipinitialbootstrap -skipstreamingdrivers -vrdisable -nofriendsui -oldtraymenu -cef-disable-gpu -silent'
  300. $steam_options = "$QUICK -applaunch $APPID $video_options $extra_launch_options "
  301. if ($cloud_cfg -gt 0) { $steam_options += "+exec_async cloud "}
  302.  
  303. #:: start game (and steam if not already running)
  304. powershell.exe -nop -c "Start-Process \`"$STEAM\steam.exe\`" \`"$steam_options\`""
  305.  
  306. #:: restore res after game closes if it was changed
  307. if ($do_not_set_desktop_res_to_match_game -le 0 -and -not $sameres) {
  308.   sc "$GAMEDIR\cfg\SetRes.cfg" "$sdl_idx,$screen,$restore_width,$restore_height,$restore_refresh,`r`n" -force -ea 0
  309.   "`n will restore res to $restore_width x $restore_height ${restore_refresh}Hz after $($APPNAME.ToUpper()) closes..."
  310.   while ($null -eq ($wait = ps $APPNAME -ea 0)) { sleep -m 250 }
  311.   $change  = [SetRes.Displays]::Change(1, $screen, $width, $height, $refresh)
  312.   if ($do_not_hide_script_window_on_waiting -le 0) { sleep 5; powershell -win 1 -nop -c ';' }
  313.   while (-not $wait.HasExited) { sleep 5 }
  314.   $restore = [SetRes.Displays]::Change(1, $screen, $restore_width, $restore_height, $restore_refresh)
  315.   del "$GAMEDIR\cfg\SetRes.cfg" -force -ea 0
  316. } else {
  317.   #:: change even if res matches, to address a rare bug where game starts in a blank window and can only \ q-tab enter out of it
  318.   $change  = [SetRes.Displays]::Change(1, $screen, $restore_width, $restore_height, $restore_refresh)
  319. }
  320. " can enter: max for $($oldres[5])x$($oldres[6]) or: min for 1024x768 if needed"
  321.  
  322. #:: done, script closes
  323. if ($do_not_hide_script_window_on_waiting -ge 1) { return }
  324. [Environment]::Exit(0)
  325.  
  326. <#:LIBRARY1: start <# ------------------------------------------------------------------------------ switch syntax highlight to C#
  327. /// SetRes - loosely based on code by Rick Strahl
  328. using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Linq; using System.Reflection;
  329. [assembly:AssemblyVersion("2024.3.10.0")] [assembly: AssemblyTitle("AveYo")]
  330. namespace SetRes
  331. {
  332.   public static class Displays
  333.   {
  334.     private const short CCDEVICENAME = 32,  CCFORMNAME  = 32;
  335.  
  336.     public const int SUCCESS       = 0,  ENUM_CURRENT  = -1,  MONITOR_DEFAULTTONEAREST = 0x00000002;
  337.     public const int DMDFO_DEFAULT = 0,  DMDFO_STRETCH =  1,  DMDFO_CENTER = 2;
  338.     public const int DMDO_DEFAULT  = 0,  DMDO_90       =  1,  DMDO_180     = 2,  DMDO_270 = 3;
  339.  
  340.     [Flags()]
  341.     private enum EdsFlags : int
  342.     {
  343.       EDS_ATTACHEDTODESKTOP = 0x00000001,  EDS_MULTIDRIVER   = 0x00000002,  EDS_PRIMARYDEVICE = 0x00000004,
  344.       EDS_MIRRORINGDRIVER   = 0x00000008,  EDS_VGACOMPATIBLE = 0x00000010,  EDS_REMOVABLE     = 0x00000020,
  345.       EDS_MODESPRUNED       = 0x08000000,  EDS_REMOTE        = 0x04000000,  EDS_DISCONNECT    = 0x02000000
  346.     }
  347.  
  348.     [Flags()]
  349.     private enum CdsFlags : uint
  350.     {
  351.       CDS_NONE            = 0x00000000,  CDS_UPDATEREGISTRY      = 0x00000001,  CDS_TEST                 = 0x00000002,
  352.       CDS_FULLSCREEN      = 0x00000004,  CDS_GLOBAL              = 0x00000008,  CDS_SET_PRIMARY          = 0x00000010,
  353.       CDS_VIDEOPARAMETERS = 0x00000020,  CDS_ENABLE_UNSAFE_MODES = 0x00000100,  CDS_DISABLE_UNSAFE_MODES = 0x00000200,
  354.       CDS_RESET           = 0x40000000,  CDS_RESET_EX            = 0x20000000,  CDS_NORESET             = 0x10000000
  355.     }
  356.  
  357.     [Flags()]
  358.     private enum DmFlags : int
  359.     {
  360.       DM_ORIENTATION   = 0x00000001,  DM_PAPERSIZE          = 0x00000002,  DM_PAPERLENGTH        = 0x00000004,
  361.       DM_PAPERWIDTH    = 0x00000008,  DM_SCALE              = 0x00000010,  DM_POSITION           = 0x00000020,
  362.       DM_NUP           = 0x00000040,  DM_DISPLAYORIENTATION = 0x00000080,  DM_COPIES             = 0x00000100,
  363.       DM_DEFAULTSOURCE = 0x00000200,  DM_PRINTQUALITY       = 0x00000400,  DM_COLOR              = 0x00000800,
  364.       DM_DUPLEX        = 0x00001000,  DM_YRESOLUTION        = 0x00002000,  DM_TTOPTION           = 0x00004000,
  365.       DM_COLLATE       = 0x00008000,  DM_FORMNAME           = 0x00010000,  DM_LOGPIXELS          = 0x00020000,
  366.       DM_BITSPERPEL    = 0x00040000,  DM_PELSWIDTH          = 0x00080000,  DM_PELSHEIGHT         = 0x00100000,
  367.       DM_DISPLAYFLAGS  = 0x00200000,  DM_DISPLAYFREQUENCY   = 0x00400000,  DM_ICMMETHOD          = 0x00800000,
  368.       DM_ICMINTENT     = 0x01000000,  DM_MEDIATYPE          = 0x02000000,  DM_DITHERTYPE         = 0x04000000,
  369.       DM_PANNINGWIDTH  = 0x08000000,  DM_PANNINGHEIGHT      = 0x10000000,  DM_DISPLAYFIXEDOUTPUT = 0x20000000
  370.     }
  371.  
  372.     [StructLayout(LayoutKind.Sequential)]
  373.     public struct POINTL { public int x; public int y; }
  374.  
  375.     [StructLayout(LayoutKind.Sequential)]
  376.     public struct RECT { public int left; public int top; public int right; public int bottom; }
  377.  
  378.     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
  379.     private struct DISPLAY_DEVICE
  380.     {
  381.       [MarshalAs(UnmanagedType.U4)]                       public int      cb;
  382.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]  public string   DeviceName;
  383.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string   DeviceString;
  384.       [MarshalAs(UnmanagedType.U4)]                       public EdsFlags StateFlags;
  385.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string   DeviceID;
  386.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string   DeviceKey;
  387.       public void Initialize()
  388.       {
  389.         this.DeviceName   = new string(new char[32]);
  390.         this.DeviceString = new string(new char[128]);
  391.         this.DeviceID     = new string(new char[128]);
  392.         this.DeviceKey    = new string(new char[128]);
  393.         this.cb           = Marshal.SizeOf(this);
  394.       }
  395.     }
  396.  
  397.     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
  398.     private struct DEVMODE
  399.     {
  400.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=CCDEVICENAME)]
  401.                                     public string  dmDeviceName;
  402.       [MarshalAs(UnmanagedType.U2)] public ushort  dmSpecVersion;
  403.       [MarshalAs(UnmanagedType.U2)] public ushort  dmDriverVersion;
  404.       [MarshalAs(UnmanagedType.U2)] public ushort  dmSize;
  405.       [MarshalAs(UnmanagedType.U2)] public ushort  dmDriverExtra;
  406.       [MarshalAs(UnmanagedType.U4)] public DmFlags dmFields;
  407.                                     public POINTL  dmPosition;
  408.       [MarshalAs(UnmanagedType.U4)] public uint    dmDisplayOrientation;
  409.       [MarshalAs(UnmanagedType.U4)] public uint    dmDisplayFixedOutput;
  410.       [MarshalAs(UnmanagedType.I2)] public short   dmColor;
  411.       [MarshalAs(UnmanagedType.I2)] public short   dmDuplex;
  412.       [MarshalAs(UnmanagedType.I2)] public short   dmYResolution;
  413.       [MarshalAs(UnmanagedType.I2)] public short   dmTTOption;
  414.       [MarshalAs(UnmanagedType.I2)] public short   dmCollate;
  415.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst=CCFORMNAME)]
  416.                                     public string  dmFormName;
  417.       [MarshalAs(UnmanagedType.U2)] public ushort  dmLogPixels;
  418.       [MarshalAs(UnmanagedType.U4)] public uint    dmBitsPerPel;
  419.       [MarshalAs(UnmanagedType.U4)] public uint    dmPelsWidth;
  420.       [MarshalAs(UnmanagedType.U4)] public uint    dmPelsHeight;
  421.       [MarshalAs(UnmanagedType.U4)] public uint    dmDisplayFlags;
  422.       [MarshalAs(UnmanagedType.U4)] public uint    dmDisplayFrequency;
  423.       [MarshalAs(UnmanagedType.U4)] public uint    dmICMMethod;
  424.       [MarshalAs(UnmanagedType.U4)] public uint    dmICMIntent;
  425.       [MarshalAs(UnmanagedType.U4)] public uint    dmMediaType;
  426.       [MarshalAs(UnmanagedType.U4)] public uint    dmDitherType;
  427.       [MarshalAs(UnmanagedType.U4)] public uint    dmReserved1;
  428.       [MarshalAs(UnmanagedType.U4)] public uint    dmReserved2;
  429.       [MarshalAs(UnmanagedType.U4)] public uint    dmPanningWidth;
  430.       [MarshalAs(UnmanagedType.U4)] public uint    dmPanningHeight;
  431.       public void Initialize()
  432.       {
  433.         this.dmDeviceName = new string(new char[CCDEVICENAME]);
  434.         this.dmFormName   = new string(new char[CCFORMNAME]);
  435.         this.dmSize       = (ushort)Marshal.SizeOf(this);
  436.       }
  437.     }
  438.  
  439.     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
  440.     private struct MONITORINFOEX
  441.     {
  442.       public uint cbSize;
  443.       public RECT rcMonitor;
  444.       public RECT rcWork;
  445.       public int dwFlags;
  446.       [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szDevice;
  447.       public void Initialize()
  448.       {
  449.         this.rcMonitor = new RECT();
  450.         this.rcWork    = new RECT();
  451.         this.szDevice  = new string(new char[32]);
  452.         this.cbSize    = (uint)Marshal.SizeOf(this);
  453.       }
  454.     }
  455.  
  456.     [DllImport("kernel32", ExactSpelling = true)] private static extern IntPtr
  457.     GetConsoleWindow();
  458.  
  459.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  460.     GetWindowRect(IntPtr hWnd, out RECT lpRect);
  461.  
  462.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  463.     MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
  464.  
  465.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  466.     GetCursorPos(out POINTL lpPoint);
  467.  
  468.     [DllImport("user32", SetLastError = true)] private static extern IntPtr
  469.     MonitorFromPoint(POINTL pt, int dwFlags);
  470.  
  471.     [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
  472.     [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  473.     GetMonitorInfo(IntPtr hMonitor, [In, Out] ref MONITORINFOEX lpmi);
  474.  
  475.     [DllImport("user32", CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  476.     EnumDisplayMonitors(IntPtr hdc, IntPtr lpRect, EnumDisplayMonitorsDelegate lpfnEnum, IntPtr dwData);
  477.  
  478.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  479.     EnumDisplayDevices(string lpDevice, uint iDevNum, ref DISPLAY_DEVICE lpDisplayDevice, uint dwFlags);
  480.  
  481.     [DllImport("user32", SetLastError=true, BestFitMapping=false, ThrowOnUnmappableChar=true)]
  482.     [return: MarshalAs(UnmanagedType.Bool)] private static extern bool
  483.     EnumDisplaySettings(byte[] lpszDeviceName, [param: MarshalAs(UnmanagedType.U4)] int iModeNum, [In,Out] ref DEVMODE lpDevMode);
  484.  
  485.     [DllImport("user32")] private static extern int
  486.     ChangeDisplaySettingsEx(string lpszDeviceName, ref DEVMODE lpDevMode, IntPtr hwnd, CdsFlags dwflags, IntPtr lParam);
  487.  
  488.     //[DllImport("user32")] private static extern int
  489.     //ChangeDisplaySettingsEx(IntPtr lpszDeviceName, IntPtr lpDevMode, IntPtr hwnd, int dwflags, IntPtr lParam);
  490.  
  491.     [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool
  492.     SetProcessDPIAware();
  493.  
  494.     private delegate bool EnumDisplayMonitorsDelegate(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData);
  495.  
  496.     private static IntPtr consolehWnd = GetConsoleWindow();
  497.  
  498.     public static class StringExtensions
  499.     {
  500.       public static byte[] ToLPTStr(string str)
  501.       {
  502.         return (str == null) ? null : Array.ConvertAll((str + '\0').ToCharArray(), Convert.ToByte);
  503.       }
  504.     }
  505.  
  506.     public class DisplayInfo
  507.     {
  508.       public int    Index      { get; set; }
  509.       public int    SDLIndex   { get; set; }
  510.       public string DeviceName { get; set; }
  511.       public int    Height     { get; set; }
  512.       public int    Width      { get; set; }
  513.       public RECT   Bounds     { get; set; }
  514.       public RECT   WorkArea   { get; set; }
  515.       public bool   IsPrimary  { get; set; }
  516.       public bool   IsCurrent  { get; set; }
  517.  
  518.       public override string ToString()
  519.       {
  520.         return string.Format("{0} {1} {2} {3} {4} ({5},{6},{7},{8}){9}{10}", Index, SDLIndex, DeviceName,
  521.           Height, Width, Bounds.left, Bounds.top, Bounds.right, Bounds.bottom,
  522.           IsPrimary ? " [primary]" : "", IsCurrent ? " [current]" : !!)
  523.       }
  524.     }
  525.  
  526.     public class DisplayDevice
  527.     {
  528.       public int    Index        { get; set; }
  529.       public int    MonitorIndex { get; set; }
  530.       public int    SDLIndex     { get; set; }
  531.       public string Id           { get; set; }
  532.       public string DriverName   { get; set; }
  533.       public string DisplayName  { get; set; }
  534.       public string AdapterName  { get; set; }
  535.       public RECT   Bounds       { get; set; }
  536.       public bool   IsPrimary    { get; set; }
  537.       public bool   IsCurrent    { get; set; }
  538.  
  539.       public override string ToString()
  540.       {
  541.         return ToString(false);
  542.       }
  543.       public string ToString(bool Detail)
  544.       {
  545.         if (Detail)
  546.         {
  547.           var sb = new System.Text.StringBuilder(9);
  548.           sb.AppendFormat(" Index:        {0}\n", Index);
  549.           sb.AppendFormat(" MonitorIndex: {0}\n", MonitorIndex);
  550.           sb.AppendFormat(" SDLIndex:     {0}\n", SDLIndex);
  551.           sb.AppendFormat(" Id:           {0}\n", Id);
  552.           sb.AppendFormat(" DriverName:   {0}\n", DriverName);
  553.           sb.AppendFormat(" DisplayName:  {0}\n", DisplayName);
  554.           sb.AppendFormat(" AdapterName:  {0}\n", AdapterName);
  555.           sb.AppendFormat(" Resolution:   {0} x {1}\n", Bounds.right - Bounds.left, Bounds.bottom - Bounds.top);
  556.           sb.AppendFormat(" Bounds:       {0},{1},{2},{3}\n", Bounds.left, Bounds.top, Bounds.right, Bounds.bottom);
  557.           sb.AppendFormat(" IsPrimary:    {0}\n", IsPrimary);
  558.           sb.AppendFormat(" IsCurrent:    {0}\n", IsCurrent);
  559.           return sb.ToString();
  560.         }
  561.         return string.Format(" {0} {1} {2} - {3}{4}{5}", MonitorIndex, SDLIndex, AdapterName, DisplayName,
  562.           IsPrimary ? " [primary]" : "", IsCurrent ? " [current]" : !!)
  563.       }
  564.     }
  565.  
  566.     public class DisplaySettings
  567.     {
  568.       public int  Index       { get; set; }
  569.       public uint Width       { get; set; }
  570.       public uint Height      { get; set; }
  571.       public uint Refresh     { get; set; }
  572.       public uint Orientation { get; set; }
  573.       public uint FixedOutput { get; set; }
  574.  
  575.       public override string ToString()
  576.       {
  577.         return ToString(false);
  578.       }
  579.  
  580.       public string ToString(bool Detail)
  581.       {
  582.         var culture = System.Globalization.CultureInfo.CurrentCulture;
  583.         if (!Detail)
  584.           return string.Format(culture, "   {0,4} x {1,4}", Width, Height);
  585.  
  586.         var degrees = Orientation == DMDO_90  ? " 90\u00b0" : Orientation == DMDO_180 ? " 180\u00b0" :
  587.           Orientation == DMDO_270 ? " 270\u00b0" : !!
  588.         var scaling = FixedOutput == DMDFO_CENTER ? " C" : FixedOutput == DMDFO_STRETCH ? " F" : !!
  589.         return string.Format(culture, "   {0,4} x {1,4} {2,3}Hz {3}{4}", Width, Height, Refresh, degrees, scaling);
  590.       }
  591.  
  592.       public override bool Equals(object d)
  593.       {
  594.         var disp = d as DisplaySettings;
  595.         return (disp.Width == Width && disp.Height == Height && disp.Refresh == Refresh && disp.Orientation == Orientation);
  596.       }
  597.  
  598.       public override int GetHashCode()
  599.       {
  600.         return (string.Format("W{0}H{1}R{2}O{3}", Width, Height, Refresh, Orientation)).GetHashCode();
  601.       }
  602.     }
  603.  
  604.     private static DEVMODE GetDeviceMode(string deviceName = null)
  605.     {
  606.       var mode = new DEVMODE();
  607.       mode.Initialize();
  608.  
  609.       if (EnumDisplaySettings(StringExtensions.ToLPTStr(deviceName), ENUM_CURRENT, ref mode))
  610.         return mode;
  611.       else
  612.         throw new InvalidOperationException(":(");
  613.     }
  614.  
  615.     private static DisplaySettings CreateDisplaySettingsObject(int idx, DEVMODE mode)
  616.     {
  617.       return new DisplaySettings()
  618.       {
  619.         Index       = idx,
  620.         Width       = mode.dmPelsWidth,
  621.         Height      = mode.dmPelsHeight,
  622.         Refresh     = mode.dmDisplayFrequency,
  623.         Orientation = mode.dmDisplayOrientation,
  624.         FixedOutput = mode.dmDisplayFixedOutput
  625.       };
  626.     }
  627.  
  628.     public static List<DisplayDevice> GetAllDisplayDevices()
  629.     {
  630.       var list = new List<DisplayDevice>();
  631.       uint idx = 0;
  632.       uint size = 256;
  633.       var device = new DISPLAY_DEVICE();
  634.       device.Initialize();
  635.  
  636.       /// AveYo: detect current monitor via cursor pointer and save Bounds rect for all
  637.       var currentCursorP = new POINTL();
  638.       GetCursorPos(out currentCursorP);
  639.       var currentMonitor = MonitorFromPoint(currentCursorP, MONITOR_DEFAULTTONEAREST);
  640.       var currentMonInfo = new MONITORINFOEX();
  641.       currentMonInfo.Initialize();
  642.       var currentDevice = GetMonitorInfo(currentMonitor, ref currentMonInfo) ? currentMonInfo.szDevice : !!
  643.  
  644.       var monitors = new List<DisplayInfo>();
  645.       EnumDisplayMonitors( IntPtr.Zero, IntPtr.Zero,
  646.         delegate (IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor,  IntPtr dwData)
  647.         {
  648.           var mi = new MONITORINFOEX();
  649.           mi.Initialize();
  650.           var success = GetMonitorInfo(hMonitor, ref mi);
  651.           if (success)
  652.           {
  653.             var di = new DisplayInfo();
  654.             di.Index      = monitors.Count + 1;
  655.             di.SDLIndex   = monitors.Count + 1;
  656.             di.DeviceName = mi.szDevice;
  657.             di.Width      = mi.rcMonitor.right - mi.rcMonitor.left;
  658.             di.Height     = mi.rcMonitor.bottom - mi.rcMonitor.top;
  659.             di.Bounds     = mi.rcMonitor;
  660.             di.WorkArea   = mi.rcWork;
  661.             di.IsPrimary  = (mi.dwFlags > 0);
  662.             di.IsCurrent  = (mi.szDevice == currentDevice);
  663.             monitors.Add(di);
  664.           }
  665.           return true;
  666.         }, IntPtr.Zero
  667.       );
  668.  
  669.       /// AveYo: calculate equivalent for sdl_displayindex to use as game launch option
  670.       var primary = monitors.FirstOrDefault(d => d.IsPrimary == true);
  671.       primary.SDLIndex = 0;
  672.       if (primary.Index == 1) {
  673.         for (var i = 1; i < monitors.Count; i++) { monitors[i].SDLIndex = i; }
  674.       }
  675.       else if (primary.Index <= monitors.Count - 1) {
  676.         for (var i = primary.Index; i <= monitors.Count - 1; i++) { monitors[i].SDLIndex = i; }
  677.       }
  678.       //foreach (var mon in monitors) Console.WriteLine(mon.ToString());
  679.  
  680.       while (EnumDisplayDevices(null, idx, ref device, size) )
  681.       {
  682.         if (device.StateFlags.HasFlag(EdsFlags.EDS_ATTACHEDTODESKTOP))
  683.         {
  684.           var isPrimary  = device.StateFlags.HasFlag(EdsFlags.EDS_PRIMARYDEVICE);
  685.           var isCurrent  = currentDevice != "" ? (device.DeviceName == currentDevice) : !REG3XP0!>isPrimary;
  686.           var monitor = monitors.FirstOrDefault(d => d.DeviceName == device.DeviceName);
  687.           var deviceName = device.DeviceName; var deviceString = device.DeviceString;
  688.  
  689.           EnumDisplayDevices(device.DeviceName, 0, ref device, 0);
  690.           var dev = new DisplayDevice()
  691.           {
  692.             Index        = list.Count + 1,
  693.             MonitorIndex = monitor.Index > 0 ? monitor.Index : list.Count + 1,
  694.             SDLIndex     = monitor.Index > 0 ? monitor.SDLIndex : list.Count + 1,
  695.             Id           = device.DeviceID,
  696.             DriverName   = deviceName,
  697.             DisplayName  = device.DeviceString,
  698.             AdapterName  = deviceString,
  699.             Bounds       = monitor.Bounds,
  700.             IsPrimary    = isPrimary,
  701.             IsCurrent    = isCurrent
  702.           };
  703.           list.Add(dev);
  704.         }
  705.         idx++;
  706.         device = new DISPLAY_DEVICE();
  707.         device.Initialize();
  708.       }
  709.       return list;
  710.     }
  711.  
  712.     public static List<DisplaySettings> GetAllDisplaySettings(string deviceName = null)
  713.     {
  714.       var list = new List<DisplaySettings>();
  715.       DEVMODE mode = new DEVMODE();
  716.       mode.Initialize();
  717.       int idx = 0;
  718.  
  719.       while (EnumDisplaySettings(StringExtensions.ToLPTStr(deviceName), idx, ref mode))
  720.         list.Add(CreateDisplaySettingsObject(idx++, mode));
  721.       return list;
  722.     }
  723.  
  724.     public static DisplaySettings GetCurrentSettings(string deviceName = null)
  725.     {
  726.       return CreateDisplaySettingsObject(-1, GetDeviceMode(deviceName));
  727.     }
  728.  
  729.     public static DisplaySettings GetCurrentDisplaySetting(string deviceName = null)
  730.     {
  731.       var mode = GetDeviceMode(deviceName);
  732.       return CreateDisplaySettingsObject(0, mode);
  733.     }
  734.  
  735.     public static int[] List(int Output = 1, int Screen = -1, int MinWidth = 1024, int MaxWidth = 16384, int MaxHeight = 16384)
  736.     {
  737.       var devices = GetAllDisplayDevices();
  738.       var monitor = devices.FirstOrDefault(d => d.IsCurrent);
  739.       if (Screen > 0 && Screen <= devices.Count) monitor = devices.FirstOrDefault(d => d.MonitorIndex == Screen);
  740.  
  741.       if (Output != 0) foreach (var display in devices) Console.WriteLine(display.ToString());
  742.  
  743.       var displayModes = GetAllDisplaySettings(monitor.DriverName);
  744.       var current      = GetCurrentDisplaySetting(monitor.DriverName);
  745.       IList<DisplaySettings> filtered = displayModes;
  746.  
  747.       /// AveYo: MaxWidth & MaxHeight are used to aggregate the list further by Refresh rate
  748.       if (Output == 1)
  749.       {
  750.         filtered = displayModes
  751.           .Where(d => d.Width >= MinWidth && d.Width <= MaxWidth && d.Height <= MaxHeight && d.Orientation == current.Orientation)
  752.           .OrderByDescending(d => d.Width).ThenByDescending(d => d.Refresh)
  753.           .GroupBy(d => new {d.Width, d.Height}).Select(g => g.First()).ToList();
  754.       }
  755.       else if (Output == 2 || Output == 0 && MaxWidth != 16384)
  756.       {
  757.         filtered = displayModes
  758.           .Where(d => d.Width >= MinWidth && d.Width <= MaxWidth && d.Height <= MaxHeight)
  759.           .OrderByDescending(d => d.Width).ThenByDescending(d => d.Refresh).ToList();
  760.       }
  761.  
  762.       if (filtered.Count == 0)
  763.         filtered.Add(current);
  764.  
  765.       var max = filtered.Aggregate((top, atm) => {
  766.           return atm.Width > top.Width || atm.Height > top.Height ? atm :
  767.             atm.Width == top.Width && atm.Height == top.Height && atm.Refresh > top.Refresh ? atm : !!
  768.       });
  769.  
  770.       foreach (var set in filtered)
  771.       {
  772.         if (set.Equals(current))
  773.         {
  774.           if (Output != 0) Console.WriteLine(set.ToString(true) + " [current]");
  775.         }
  776.         else
  777.         {
  778.           if (Output != 0) Console.WriteLine(set.ToString(true));
  779.         }
  780.       }
  781.       if (Output != 0) Console.WriteLine();
  782.       return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  783.         (int)current.Width, (int)current.Height, (int)current.Refresh, (int)max.Width, (int)max.Height, (int)max.Refresh };
  784.     }
  785.  
  786.     public static int[] Change(int Output = 1, int Screen = -1, int Width = 0, int Height = 0, decimal Refresh = 0, int Test = 0)
  787.     {
  788.       var devices = GetAllDisplayDevices();
  789.       var monitor = devices.FirstOrDefault(d => d.IsCurrent);
  790.       if (Screen > 0 && Screen <= devices.Count) monitor = devices.FirstOrDefault(d => d.MonitorIndex == Screen);
  791.  
  792.       var deviceName = monitor.DriverName;
  793.       var current    = GetCurrentDisplaySetting(deviceName);
  794.       //var position = new POINTL(); position.x = monitor.Bounds.left; position.y = monitor.Bounds.top;
  795.  
  796.       if (Width == 0 || Height == 0)
  797.       {
  798.         if (Output != 0) Console.WriteLine(" Width and Height parameters required.\n");
  799.         return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  800.           (int)current.Width, (int)current.Height, (int)current.Refresh, 0, 0, 0, 1 };
  801.       }
  802.  
  803.       /// AveYo: Refresh fallback from fractional ex: 59.976 - to nearest integer ex: 60 - to highest supported
  804.       uint Orientation = 0, FixedOutput = 0, Temporary = 0; /// for testing
  805.       var displayModes = GetAllDisplaySettings(deviceName);
  806.       var filtered = displayModes
  807.         .Where(d => d.Width == Width && d.Height == Height && d.Orientation == current.Orientation)
  808.         .OrderByDescending(d => d.Width).ThenByDescending(d => d.Refresh).ToList();
  809.  
  810.       var ref1 = filtered.FirstOrDefault(d => d.Refresh == (uint)Decimal.Truncate(Refresh));
  811.       var ref2 = filtered.FirstOrDefault(d => d.Refresh == (uint)Decimal.Truncate(Refresh + 1));
  812.       var set = Refresh == 0 ? filtered.FirstOrDefault() : ref1 != null ? ref1 : class="re0">ref2 != null ? ref2 : !REG3XP0!>filtered.FirstOrDefault();
  813.       if (set == null)
  814.       {
  815.         /// AveYo: Resolution fallback to current
  816.         if (Output != 0) Console.WriteLine(" No matching display mode!\n");
  817.         set = current;
  818.         return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  819.           (int)set.Width, (int)set.Height, (int)set.Refresh, (int)set.Width, (int)set.Height, (int)set.Refresh, 2 };
  820.       }
  821.  
  822.       try
  823.       {
  824.         DEVMODE mode = GetDeviceMode(deviceName);
  825.         //mode.dmPosition           = position;
  826.         mode.dmPelsWidth          = set.Width;
  827.         mode.dmPelsHeight         = set.Height;
  828.         mode.dmDisplayFrequency   = set.Refresh;
  829.         mode.dmDisplayOrientation = Orientation > 0 ? Orientation : set.Orientation;
  830.         mode.dmDisplayFixedOutput = FixedOutput > 0 ? FixedOutput : set.FixedOutput;
  831.         mode.dmFields             = DmFlags.DM_PELSWIDTH | DmFlags.DM_PELSHEIGHT; //DmFlags.DM_POSITION
  832.         if (Refresh > 0)     mode.dmFields |= DmFlags.DM_DISPLAYFREQUENCY;
  833.         if (FixedOutput > 0) mode.dmFields |= DmFlags.DM_DISPLAYORIENTATION;
  834.         if (Temporary > 0)   mode.dmFields |= DmFlags.DM_DISPLAYFIXEDOUTPUT;
  835.  
  836.         /// AveYo: test and apply the target res even if it's the same as the current one
  837.         CdsFlags flags = CdsFlags.CDS_TEST | CdsFlags.CDS_RESET | CdsFlags.CDS_UPDATEREGISTRY; //CdsFlags.CDS_NORESET
  838.         if (Temporary > 0) flags |= CdsFlags.CDS_FULLSCREEN;
  839.  
  840.         int result = ChangeDisplaySettingsEx(deviceName, ref mode, IntPtr.Zero, flags, IntPtr.Zero);
  841.         if (Test != 0)
  842.           return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  843.             (int)current.Width, (int)current.Height, (int)current.Refresh, (int)set.Width, (int)set.Height, (int)set.Refresh, 0 };
  844.         if (result != SUCCESS)
  845.           throw new InvalidOperationException(string.Format("{0} : {1} = N/A", set.ToString(true), monitor.DisplayName));
  846.         flags &= ~CdsFlags.CDS_TEST;
  847.         result = ChangeDisplaySettingsEx(deviceName, ref mode, IntPtr.Zero, flags, IntPtr.Zero);
  848.         if (result != SUCCESS)
  849.           throw new InvalidOperationException(string.Format("{0} : {1} = FAIL", set.ToString(true), monitor.DisplayName));
  850.  
  851.         //ChangeDisplaySettingsEx(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero);
  852.         if (Output != 0) Console.WriteLine(string.Format("{0} : class="re0">{1} = OK", set.ToString(true), monitor.DisplayName));
  853.         return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  854.           (int)current.Width, (int)current.Height, (int)current.Refresh, (int)set.Width, (int)set.Height, (int)set.Refresh, 0 };
  855.       }
  856.       catch(Exception ex)
  857.       {
  858.         if (Output != 0) Console.WriteLine(ex.Message);
  859.         return new int[] { monitor.SDLIndex, monitor.MonitorIndex,
  860.           (int)current.Width, (int)current.Height, (int)current.Refresh, 0, 0, 0, 3 };
  861.       }
  862.     }
  863.  
  864.     public static int[] Init(int Screen = -1)
  865.     {
  866.       SetProcessDPIAware(); /// AveYo: calculate using real screen values, not windows dpi scaling ones
  867.       var devices = GetAllDisplayDevices();
  868.       var monitor = devices.FirstOrDefault(d => d.IsCurrent);
  869.       if (Screen > 0 && Screen <= devices.Count) monitor = devices.FirstOrDefault(d => d.MonitorIndex == Screen);
  870.       RECT cR = new RECT(), mR = monitor.Bounds;
  871.       GetWindowRect(consolehWnd, out cR);
  872.       /// AveYo: move console window to Screen index or currently active
  873.       MoveWindow(consolehWnd, mR.left + 100, mR.top + 100, cR.right - cR.left, cR.bottom - cR.top, true);
  874.       return new int[] { monitor.SDLIndex, monitor.MonitorIndex, monitor.IsPrimary ? 1 : 0, devices.Count };
  875.     }
  876.   }
  877. }
  878. <#:LIBRARY1: end -------------------------------------------------------------------------------------------------------------- #>
  879. $_press_enter_if_copy_pasted_to_powershell
  880.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement