From dba8a1e6722814d294f2ff4b29faec2054866770 Mon Sep 17 00:00:00 2001 From: Tomas Date: Sat, 13 Dec 2025 18:19:55 +0100 Subject: [PATCH] Initial commit --- .gitignore | 363 ++++++++++++++++++++++++++++++++++ Display.cpp | 43 ++++ Display.h | 24 +++ Exception.h | 66 +++++++ Main.cpp | 246 +++++++++++++++++++++++ UpdateDisplay.sln | 31 +++ UpdateDisplay.vcxproj | 136 +++++++++++++ UpdateDisplay.vcxproj.filters | 33 ++++ 8 files changed, 942 insertions(+) create mode 100644 .gitignore create mode 100644 Display.cpp create mode 100644 Display.h create mode 100644 Exception.h create mode 100644 Main.cpp create mode 100644 UpdateDisplay.sln create mode 100644 UpdateDisplay.vcxproj create mode 100644 UpdateDisplay.vcxproj.filters diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/Display.cpp b/Display.cpp new file mode 100644 index 0000000..c2de82f --- /dev/null +++ b/Display.cpp @@ -0,0 +1,43 @@ +#include "Display.h" +#include "Exception.h" + + +Display::Display() +{ + _devmode.dmSize = sizeof(DEVMODE); + + BOOL success = EnumDisplaySettingsEx( + nullptr, + ENUM_CURRENT_SETTINGS, + &_devmode, + 0 + ); + + if (!success) + throw SystemException(GetLastError()); +} + + +void Display::rotate(Rotation rot) +{ + DWORD& orient = _devmode.dmDisplayOrientation; + DWORD& width = _devmode.dmPelsWidth; + DWORD& height = _devmode.dmPelsHeight; + + if (orient == DMDO_90 || orient == DMDO_270) + std::swap(width, height); + + orient = (DWORD)rot; + + if (orient == DMDO_90 || orient == DMDO_270) + std::swap(width, height); +} + + +void Display::apply() +{ + LONG res = ChangeDisplaySettingsEx(nullptr, &_devmode, nullptr, CDS_RESET, nullptr); + + if (res != DISP_CHANGE_SUCCESSFUL) + throw DisplayException(res); +} \ No newline at end of file diff --git a/Display.h b/Display.h new file mode 100644 index 0000000..0dafb93 --- /dev/null +++ b/Display.h @@ -0,0 +1,24 @@ +#pragma once + +#include + + +class Display +{ +public: + enum class Rotation + { + ROTATE_0 = DMDO_DEFAULT, + ROTATE_90 = DMDO_90, + ROTATE_180 = DMDO_180, + ROTATE_270 = DMDO_270, + }; + + Display(); + + void rotate(Rotation rot); + void apply(); + +private: + DEVMODE _devmode = { 0 }; +}; \ No newline at end of file diff --git a/Exception.h b/Exception.h new file mode 100644 index 0000000..0da37d2 --- /dev/null +++ b/Exception.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include +#include + + +// For windows system errors +class SystemException : public std::exception +{ +public: + SystemException(DWORD error) : _error(error) + { + char buffer[2048]; + FormatMessageA( + FORMAT_MESSAGE_FROM_SYSTEM, + nullptr, + error, + LANG_USER_DEFAULT, + buffer, + sizeof(buffer), + nullptr + ); + _message = std::string(buffer); + } + + virtual const char* what() const { return _message.c_str(); } + virtual DWORD error() const { return _error; } + +private: + DWORD _error; + std::string _message; +}; + + +// For display errors (ChangeDisplaySettingsExA) +class DisplayException : public std::exception +{ +public: + DisplayException(DWORD error) : _error(error), _message(_num2str(error)) + { + } + + virtual const char* what() const { return _message; } + virtual DWORD error() const { return _error; } + +private: + static const char* _num2str(DWORD error) + { + switch (error) + { + case DISP_CHANGE_SUCCESSFUL: return "The settings change was successful."; + case DISP_CHANGE_BADDUALVIEW: return "The settings change was unsuccessful because the system is DualView capable."; + case DISP_CHANGE_BADFLAGS: return "An invalid set of flags was passed in."; + case DISP_CHANGE_BADMODE: return "The graphics mode is not supported."; + case DISP_CHANGE_BADPARAM: return "An invalid parameter was passed in. This can include an invalid flag or combination of flags."; + case DISP_CHANGE_FAILED: return "The display driver failed the specified graphics mode."; + case DISP_CHANGE_NOTUPDATED: return "Unable to write settings to the registry."; + case DISP_CHANGE_RESTART: return "The computer must be restarted for the graphics mode to work."; + default: return "Unknown error"; + } + } + + DWORD _error; + const char* _message; +}; \ No newline at end of file diff --git a/Main.cpp b/Main.cpp new file mode 100644 index 0000000..430da7a --- /dev/null +++ b/Main.cpp @@ -0,0 +1,246 @@ +#include +#include +#include + +#include +#include +#include + + +#include "Display.h" + + +void print_help() +{ + std::cout + << "UpdateDisplay" << std::endl + << "=============" << std::endl + << std::endl + << "Usage: UpdateDisplay.exe " << std::endl + << std::endl + << "By default the program will refresh display settings." << std::endl + << std::endl + << "Possible options:" << std::endl + << std::endl + << "--rotate" << "\t - Rotates Display" << std::endl + << "\t0" << "\t - Landscape" << std::endl + << "\t90" << "\t - Prtrait" << std::endl + << "\t180" << "\t - Flippd Landscape" << std::endl + << "\t270" << "\t - Flippd Prtrait" << std::endl + << std::endl; +} + + +void main(int argc, char** argv) +{ + if (argc == 1) + return print_help(); + + Display dis; + + char** arg = argv; + arg++; + for (int i = 1; i < argc; i++, arg++) + { + std::string a(*arg); + + if (a == "--help") + print_help(); + + else if (a == "--rotate") + { + i++; + arg++; + if (i == argc) + throw std::exception("Argumment to --rotate not specified"); + a = std::string(*arg); + + if (a == "0") + dis.rotate(Display::Rotation::ROTATE_0); + else if (a == "90") + dis.rotate(Display::Rotation::ROTATE_90); + else if (a == "180") + dis.rotate(Display::Rotation::ROTATE_180); + else if (a == "270") + dis.rotate(Display::Rotation::ROTATE_270); + else + throw std::exception(("Unknown rotation: "+a).c_str()); + } + } + + dis.apply(); +} + + +// Taken from https://stackoverflow.com/a/74999569 +static void get_command_line_args(int* argc, char*** argv) +{ + // Get the command line arguments as wchar_t strings + wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), argc); + if (!wargv) { *argc = 0; *argv = NULL; return; } + + // Count the number of bytes necessary to store the UTF-8 versions of those strings + int n = 0; + for (int i = 0; i < *argc; i++) + n += WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, NULL, 0, NULL, NULL) + 1; + + // Allocate the argv[] array + all the UTF-8 strings + *argv = (char**)malloc((*argc + 1) * sizeof(char*) + n); + if (!*argv) { *argc = 0; return; } + + // Convert all wargv[] --> argv[] + char* arg = (char*)&((*argv)[*argc + 1]); + for (int i = 0; i < *argc; i++) + { + (*argv)[i] = arg; + arg += WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, arg, n, NULL, NULL) + 1; + } + (*argv)[*argc] = NULL; +} + + +// Source - https://stackoverflow.com/a +// Posted by Roger Sanders, modified by community. See post 'Timeline' for change history +// Retrieved 2025-12-13, License - CC BY-SA 3.0 +void BindCrtHandlesToStdHandles(bool bindStdIn, bool bindStdOut, bool bindStdErr) +{ + // Re-initialize the C runtime "FILE" handles with clean handles bound to "nul". We do this because it has been + // observed that the file number of our standard handle file objects can be assigned internally to a value of -2 + // when not bound to a valid target, which represents some kind of unknown internal invalid state. In this state our + // call to "_dup2" fails, as it specifically tests to ensure that the target file number isn't equal to this value + // before allowing the operation to continue. We can resolve this issue by first "re-opening" the target files to + // use the "nul" device, which will place them into a valid state, after which we can redirect them to our target + // using the "_dup2" function. + if (bindStdIn) + { + FILE* dummyFile; + freopen_s(&dummyFile, "nul", "r", stdin); + } + if (bindStdOut) + { + FILE* dummyFile; + freopen_s(&dummyFile, "nul", "w", stdout); + } + if (bindStdErr) + { + FILE* dummyFile; + freopen_s(&dummyFile, "nul", "w", stderr); + } + + // Redirect unbuffered stdin from the current standard input handle + if (bindStdIn) + { + HANDLE stdHandle = GetStdHandle(STD_INPUT_HANDLE); + if (stdHandle != INVALID_HANDLE_VALUE) + { + int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT); + if (fileDescriptor != -1) + { + FILE* file = _fdopen(fileDescriptor, "r"); + if (file != NULL) + { + int dup2Result = _dup2(_fileno(file), _fileno(stdin)); + if (dup2Result == 0) + { + setvbuf(stdin, NULL, _IONBF, 0); + } + } + } + } + } + + // Redirect unbuffered stdout to the current standard output handle + if (bindStdOut) + { + HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); + if (stdHandle != INVALID_HANDLE_VALUE) + { + int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT); + if (fileDescriptor != -1) + { + FILE* file = _fdopen(fileDescriptor, "w"); + if (file != NULL) + { + int dup2Result = _dup2(_fileno(file), _fileno(stdout)); + if (dup2Result == 0) + { + setvbuf(stdout, NULL, _IONBF, 0); + } + } + } + } + } + + // Redirect unbuffered stderr to the current standard error handle + if (bindStdErr) + { + HANDLE stdHandle = GetStdHandle(STD_ERROR_HANDLE); + if (stdHandle != INVALID_HANDLE_VALUE) + { + int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT); + if (fileDescriptor != -1) + { + FILE* file = _fdopen(fileDescriptor, "w"); + if (file != NULL) + { + int dup2Result = _dup2(_fileno(file), _fileno(stderr)); + if (dup2Result == 0) + { + setvbuf(stderr, NULL, _IONBF, 0); + } + } + } + } + } + + // Clear the error state for each of the C++ standard stream objects. We need to do this, as attempts to access the + // standard streams before they refer to a valid target will cause the iostream objects to enter an error state. In + // versions of Visual Studio after 2005, this seems to always occur during startup regardless of whether anything + // has been read from or written to the targets or not. + if (bindStdIn) + { + std::wcin.clear(); + std::cin.clear(); + } + if (bindStdOut) + { + std::wcout.clear(); + std::cout.clear(); + } + if (bindStdErr) + { + std::wcerr.clear(); + std::cerr.clear(); + } +} + + + +int APIENTRY WinMain(HINSTANCE hInst, HINSTANCE hInstPrev, PSTR cmdline, int cmdshow) +{ + if (AttachConsole(ATTACH_PARENT_PROCESS)) + BindCrtHandlesToStdHandles(true, true, true); + + int argc = 0; + char** argv = nullptr; + try + { + get_command_line_args(&argc, &argv); + + main(argc, argv); + + if (argv) + free(argv); + + return EXIT_SUCCESS; + } + catch (std::exception& ex) + { + if (argv) + free(argv); + + MessageBoxA(nullptr, ex.what(), "UpdateDisplay error", MB_ICONERROR); + + return EXIT_FAILURE; + } +} \ No newline at end of file diff --git a/UpdateDisplay.sln b/UpdateDisplay.sln new file mode 100644 index 0000000..3b4f3f0 --- /dev/null +++ b/UpdateDisplay.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36511.14 d17.14 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UpdateDisplay", "UpdateDisplay.vcxproj", "{138CC269-88D1-4FE0-926F-492DA40C6500}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {138CC269-88D1-4FE0-926F-492DA40C6500}.Debug|x64.ActiveCfg = Debug|x64 + {138CC269-88D1-4FE0-926F-492DA40C6500}.Debug|x64.Build.0 = Debug|x64 + {138CC269-88D1-4FE0-926F-492DA40C6500}.Debug|x86.ActiveCfg = Debug|Win32 + {138CC269-88D1-4FE0-926F-492DA40C6500}.Debug|x86.Build.0 = Debug|Win32 + {138CC269-88D1-4FE0-926F-492DA40C6500}.Release|x64.ActiveCfg = Release|x64 + {138CC269-88D1-4FE0-926F-492DA40C6500}.Release|x64.Build.0 = Release|x64 + {138CC269-88D1-4FE0-926F-492DA40C6500}.Release|x86.ActiveCfg = Release|Win32 + {138CC269-88D1-4FE0-926F-492DA40C6500}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {E5CA91E3-77F9-4C35-B69F-1174265849AA} + EndGlobalSection +EndGlobal diff --git a/UpdateDisplay.vcxproj b/UpdateDisplay.vcxproj new file mode 100644 index 0000000..63a9788 --- /dev/null +++ b/UpdateDisplay.vcxproj @@ -0,0 +1,136 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {138cc269-88d1-4fe0-926f-492da40c6500} + UpdateDisplay + 10.0 + + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + Application + true + v143 + Unicode + + + Application + false + v143 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Windows + true + + + + + + + + + + + + + + \ No newline at end of file diff --git a/UpdateDisplay.vcxproj.filters b/UpdateDisplay.vcxproj.filters new file mode 100644 index 0000000..700de51 --- /dev/null +++ b/UpdateDisplay.vcxproj.filters @@ -0,0 +1,33 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + \ No newline at end of file