Jump to content
Kronitron

Detect and Switch Monitor Orientation Between Portrait and Landscape

Recommended Posts

Kronitron

     Hello AutoIt community!  First, let me say that :ILA2:

     So, my monitor easily rotates between portrait and landscape orientation; I move it around regularly.  Opening the screen manager and manually changing it got so tedious I decided to learn to code.  I had never coded anything before trying AutoIT and this is my second version of the script.  I'm actually quite proud of it.  It's versatile, works great as a standalone .exe, and doesn't require any fancy tweaking to use on different computers.   Tell me what you think!

$Desktop_Height = @DesktopHeight
$Desktop_Width = @DesktopWidth
   Run("control desk.cpl")
   WinWaitActive("Screen Resolution")
   ControlSend("Screen Resolution", "", "", "!o")
   If $Desktop_Height < $Desktop_Width Then
      ControlSend("Screen Resolution", "", "", "{Down}")
   ElseIf $Desktop_Height > $Desktop_Width Then
      ControlSend("Screen Resolution", "", "", "{Up}")
   EndIf
   ControlSend("Screen Resolution", "", "", "!a")
   WinWaitActive("Display Settings")
   ControlSend("Screen Resolution", "", "", "!k")
   WinWaitActive("Screen Resolution")
   ControlSend("Screen Resolution", "", "", "!{F4}")
Exit

I attached the .ico I use.

Edit: I replaced script v2 with v3

Landscape (Dell).ico

Edited by Kronitron

[post='1192322']Detect and Switch Monitor Orientation[/post]

Share this post


Link to post
Share on other sites
careca

Nice for the ones who can't use Shift Alt Arrow

  • Like 1

Spoiler

Paster - Main function is to paste text, but has more functions. (No longer mantained, switched to String Trigger)

Renamer - Rename files and folders, remove portions of text from the filename etc.

GPO Tool - Export/Import Group policy settings.

MirrorDir - Synchronize/Backup/Mirror Folders

BeatsPlayer - Music player.

Params Tool - Right click an exe to see it's parameters or execute them.

String Trigger - Triggers pasting text or applications or internet links on specific strings.

Inconspicuous - Hide files in plain sight, not fully encrypted.

Regedit Control - Registry browsing history, quickly jump into any saved key.

Time4Shutdown - Write the time for shutdown in minutes.

Power Profiles Tool - Set a profile as active, delete, duplicate, export and import.

Firefox Profile Backup - Backup/restore previously saved profile.

Finished Task Shutdown - Shuts down pc when specified window/Wndl/process closes.

NetworkSpeedShutdown - Shuts down pc if download speed goes under "X" Kb/s.

IUIAutomation - Topic with framework and examples

Au3Record.exe

Share this post


Link to post
Share on other sites
Mat

This is possible without automating any user interface.

If this is only your second project, then you won't have been exposed yet to the monstrosity that is the Windows API (shortened to WinAPI). The WinAPI dlls give you control over nearly everything on the system, but with great power comes great big confusing documentation pages, on a site called MSDN.

With great power also comes great ability to get your computer completely FUBAR. So with that warning in place, here is the code to rotate the screen directly with the winapi. 

Hopefully this shows you just how powerful programming can be, and why it is a great skill to learn :)

#include <APIGdiConstants.au3>
#include <WinAPIGdi.au3>

Local $i = 0, $aData

$aData = _WinAPI_EnumDisplaySettings('', $ENUM_CURRENT_SETTINGS)
ConsoleWrite('Current settings: ' & $aData[0] & ' x ' & $aData[1] & ' x ' & $aData[2] & ' bit, ' & $aData[3] & ' hz' & @CRLF)

; Store the current settings
$tDM = _WinAPI_EnumDisplaySettingsEx("", $ENUM_CURRENT_SETTINGS)


; Get the settings to change
$tDM2 = _WinAPI_EnumDisplaySettingsEx("", $ENUM_CURRENT_SETTINGS)

; Flip orientation, but also switch width/height.
$tDM2.Fields = BitOR($tDM2.Fields, $DM_DISPLAYORIENTATION)
$tDM2.DisplayOrientation = $DMDO_90
$v = $tDM2.PelsWidth
$tDM2.PelsWidth = $tDM2.PelsHeight
$tDM2.PelsHeight = $v

; Change the display settings
$ret = _WinAPI_ChangeDisplaySettings($tDM2, 0)

; Wait for the user to click ok, will also timeout after 10 seconds just in case I've messed the display up.
MsgBox(0, $ret, "H" & @LF & "e" & @LF & "l" & @LF & "l" & @LF & "o", 10)

_WinAPI_ChangeDisplaySettings($tDM, 0)
MsgBox(0, @error, "Back to normal")





Func _WinAPI_ChangeDisplaySettings($tDevMode, $dwFlags)
    Local $aRet = DllCall("user32.dll", "LONG", "ChangeDisplaySettingsW", "ptr", DllStructGetPtr($tDevMode), "DWORD", $dwFlags)
    If @error Then Return SetError(@error, @extended, 0)
    Return $aRet[0]
EndFunc   ;==>_WinAPI_ChangeDisplaySettings


; #FUNCTION# ====================================================================================================================
; Author.........: Yashied
; Modified.......: jpm, Mat
; ===============================================================================================================================
Func _WinAPI_EnumDisplaySettingsEx($sDevice, $iMode)
    Local $sTypeOfDevice = 'wstr'
    If Not StringStripWS($sDevice, $STR_STRIPLEADING + $STR_STRIPTRAILING) Then
        $sTypeOfDevice = 'ptr'
        $sDevice = 0
    EndIf

    Local $tDevMode = DllStructCreate($tagDEVMODE_DISPLAY)
    DllStructSetData($tDevMode, 'Size', DllStructGetSize($tDevMode))
    DllStructSetData($tDevMode, 'DriverExtra', 0)

    Local $aRet = DllCall('user32.dll', 'bool', 'EnumDisplaySettingsW', $sTypeOfDevice, $sDevice, 'dword', $iMode, _
            'struct*', $tDevMode)
    If @error Or Not $aRet[0] Then Return SetError(@error + 10, @extended, 0)

    Return $tDevMode
EndFunc   ;==>_WinAPI_EnumDisplaySettingsEx
  • Like 2

Share this post


Link to post
Share on other sites
Kronitron

 

This is possible without automating any user interface.

If this is only your second project, then you won't have been exposed yet to the monstrosity that is the Windows API (shortened to WinAPI). The WinAPI dlls give you control over nearly everything on the system, but with great power comes great big confusing documentation pages, on a site called MSDN.

With great power also comes great ability to get your computer completely FUBAR. So with that warning in place, here is the code to rotate the screen directly with the winapi. 

Hopefully this shows you just how powerful programming can be, and why it is a great skill to learn :)

 

I love the Spiderman references lol.  Thanks for the post, it greatly expanded my view of AutoIT's capabilities. 


[post='1192322']Detect and Switch Monitor Orientation[/post]

Share this post


Link to post
Share on other sites
mLipok

@Mat

Very good motivational speech.

mLipok


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API Forum Rules *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library
 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskScheduler

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2018-10-31

Share this post


Link to post
Share on other sites
lalder

Sorry to bring this article back from the dead- does anybody know how I could modify this code to change only one monitor in a multi-monitor setup? I'm amateur-at-best at writing script and wouldn't even know where to begin.

 

Thanks for any help!

Share this post


Link to post
Share on other sites
BetaLeaf

Hope no one minds the necro. I found this really useful and decided to rework it to fit my needs. Basically, I made it use CTRL+ALT+<ArrowKey> to rotate the display. Basically exactly the same as Intel's solution, except it works on all graphics card Windows can rotate. For me personally, my laptop uses a G-Sync panel which the monitor must be hard wired to the Nvidia GPU. Because I cannot use the integrated graphics, the hotkeys for Intel's solution do not work.  That's where this script comes in. This rotates only the primary monitor (#1 in window's display settings). Also, to answer @lalder's question, if you happen to still be hanging out here (doubt it), you can swap the primary monitors temporarily to the one you want to rotate, then swap back once you rotated them.  I hope this helps anyone looking for this.

 

#include <APIGdiConstants.au3>
#include <WinAPIGdi.au3>
#include <Misc.au3>
opt("TrayIconHide",1) ;I dont like having unnecessary icons on my tray. Feel free to disable.
$wintitle="Display Rotator"
_Singleton($wintitle)
RegWrite("HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", $wintitle, "REG_SZ", @ScriptFullPath) ;AutoStart with Windows
HotKeySet("^!{up}", "_upsidedown")
HotKeySet("^!{down}", "_Down")
HotKeySet("^!{left}", "_Left")
HotKeySet("^!{right}", "_Right")
While 1
    Sleep(60000)
WEnd
Func _WinAPI_ChangeDisplaySettings($tDevMode, $dwFlags)
    Local $aRet = DllCall("user32.dll", "LONG", "ChangeDisplaySettingsW", "ptr", DllStructGetPtr($tDevMode), "DWORD", $dwFlags)
    If @error Then Return SetError(@error, @extended, 0)
    Return $aRet[0]
EndFunc   ;==>_WinAPI_ChangeDisplaySettings
; #FUNCTION# ====================================================================================================================
; Author.........: Yashied
; Modified.......: jpm, Mat
; ===============================================================================================================================
Func _WinAPI_EnumDisplaySettingsEx($sDevice, $iMode)
    Local $sTypeOfDevice = 'wstr'
    If Not StringStripWS($sDevice, $STR_STRIPLEADING + $STR_STRIPTRAILING) Then
        $sTypeOfDevice = 'ptr'
        $sDevice = 0
    EndIf
    Local $tDevMode = DllStructCreate($tagDEVMODE_DISPLAY)
    DllStructSetData($tDevMode, 'Size', DllStructGetSize($tDevMode))
    DllStructSetData($tDevMode, 'DriverExtra', 0)
    Local $aRet = DllCall('user32.dll', 'bool', 'EnumDisplaySettingsW', $sTypeOfDevice, $sDevice, 'dword', $iMode, _
            'struct*', $tDevMode)
    If @error Or Not $aRet[0] Then Return SetError(@error + 10, @extended, 0)
    Return $tDevMode
EndFunc   ;==>_WinAPI_EnumDisplaySettingsEx
Func _Right()
    _WinAPI_ChangeDisplaySettings(_SetOrientation("Right"), 0)
EndFunc   ;==>_Right
Func _Left()
    _WinAPI_ChangeDisplaySettings(_SetOrientation("Left"), 0)
EndFunc   ;==>_Left
Func _upsidedown()
    _WinAPI_ChangeDisplaySettings(_SetOrientation("Up"), 0)
EndFunc   ;==>_upsidedown
Func _Down()
    _WinAPI_ChangeDisplaySettings(_SetOrientation("Down"), 0)
EndFunc   ;==>_Down
Func _SetOrientation($direction) ;$direction = {0 = Down, 1 = Right, 2 = Up, 3 = Left}
    Switch $direction
        Case "Left"
            $direction = 3
        Case "Right"
            $direction = 1
        Case "Up"
            $direction = 2
        Case "Down"
            $direction = 0
    EndSwitch
    $tDM2 = _WinAPI_EnumDisplaySettingsEx("", $ENUM_CURRENT_SETTINGS)
    $tDM2.Fields = BitOR($tDM2.Fields, $DM_DISPLAYORIENTATION)
    $tDM2.DisplayOrientation = $direction
    Select
        Case ($direction = 1) Or ($direction = 3)
            If $tDM2.PelsWidth > $tDM2.PelsHeight Then
                $v=$tDM2.PelsWidth
                $tDM2.PelsWidth = $tDM2.PelsHeight
                $tDM2.PelsHeight = $v
            Else
                $tDM2.PelsWidth = $tDM2.PelsWidth
                $tDM2.PelsHeight = $tDM2.PelsHeight
            EndIf
        Case ($direction = 0) Or ($direction = 2)
            If $tDM2.PelsWidth > $tDM2.PelsHeight Then
                $tDM2.PelsWidth = $tDM2.PelsWidth
                $tDM2.PelsHeight = $tDM2.PelsHeight
            Else
                $v=$tDM2.PelsWidth
                $tDM2.PelsWidth = $tDM2.PelsHeight
                $tDM2.PelsHeight = $v
            EndIf
    EndSelect
    Return $tDM2
EndFunc   ;==>_SetOrientation

Note: This writes to registry for current user to allow script to auto starts with windows. It also starts without a tray icon. Just personal preference, but you can change it as needed.

P.S. I'm curious if there is an easier or better way to do the select statement in _SetOrientation(). 

  • Like 1

False Positive Reporter - Mass email all anti virus vendors with an attachment of your program for fast and easy whitelisting.

My GitHub Page: https://github.com/BetaLeaf

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×