Home > Back-end >  Get current screen resolution using .NET Core Console Application
Get current screen resolution using .NET Core Console Application

Time:03-20

I'm using a .NET Core 3.1 console app in VS 2019. I'm trying to get current screen resolution (Windows display). I don't want to get monitor maximum resolution.

I have following batch code that works. I just want to check my resolution is 1024x768 or not.

Simply want to convert this code into true C# code without launching CMD by Process.start. I want to implement if else to check the resolution is 1024x768 or not.

Here is my batch file:

@echo off

for /f "delims=" %%# in  ('"wmic path Win32_VideoController  get CurrentHorizontalResolution,CurrentVerticalResolution /format:value"') do (
  set "%%#">nul
)

echo %CurrentHorizontalResolution%
echo %CurrentVerticalResolution%

pause

CodePudding user response:

After installing NuGet package System.Management, you can access these parameters as explained here:

    //  https://wutils.com/wmi/

    //  Install package System.Management (6.0.0)
    //  using System.Management;

    //create a management scope object
    ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");

    //create object query
    ObjectQuery query = 
        new ObjectQuery("SELECT * FROM Win32_VideoController " 
                        "Where DeviceID=\"VideoController1\"");

    //create object searcher
    ManagementObjectSearcher searcher =
        new ManagementObjectSearcher(scope, query);

    //get a collection of WMI objects
    ManagementObjectCollection queryCollection = 
        searcher.Get();

    //enumerate the collection.
    foreach (ManagementObject m in queryCollection)
    {
        // access properties of the WMI object
        Console.WriteLine("CurrentHorizontalResolution : {0}", 
            m["CurrentHorizontalResolution"]);
        Console.WriteLine("CurrentVerticalResolution : {0}", 
            m["CurrentVerticalResolution"]);
    }
  • Related