Advertisement
aveyo

CS2_launcher

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