Getting Screen Resolution

1) How do I read the current screen resolution?

Getting the current screen resolution is easy and built into the framework without having to delve into something like the GetSystemMetrics API. The Screen class contains information about all of the display devices attached to the system. So to determine the resolution of the primary monitor, you could use something like:

 Dim screenWidth as Integer = Screen.PrimaryScreen.Bounds.Width
 Dim screenHeight as Integer = Screen.PrimaryScreen.Bounds.Height

To deal with multiple monitors, look into the Screen.AllScreens property, which returns an array of Screen objects corresponding to each of the displays attached to the system. You could then determine (using the above code) the resolution of each of the displays attached to the computer by looping through the array of Screen objects.

2) How do I change the current screen resolution from my VB.NET application?

Changing the screen resolution is a little more difficult. Before going any further, I would caution you that an application adjusting the user's display resolution is unexpected and potentially creates a hostile user environment. I know that I wouldn't use an application that changed my screen resolution without permission, and I'd think long and hard about using one that required me to do so at all. If you're trying to make a screen saver, there's probably a better and easier way to do what you want. That being said, it can be done from VB.NET if you're willing to P/Invoke a few functions from the Windows API.

The simplest way if you're only concerned about the case of a single monitor is using the ChangeDisplaySettings function, which allows you to specify the graphics mode of the default display (the user's primary monitor only).

To handle the case of multiple monitors, you'll need to use the EnumDisplayDevices function to obtain information about all of the display devices attached to the computer, and the ChangeDisplaySettingsEx function to change a particular screen.

Check out pinvoke.net for how to declare the signatures of the Windows API calls in VB.NET. A Google search turned up this thread, although I haven't verified the sample code that they provide.

To modify the screen resolution only while your app is running, and then restore it when the user quits your program, you'll want to save the current screen settings before you modify them and then restore them (using the same method calls) when your application exits.


How to get current screen resolution

Public Function ScreenResolution() As String
        Dim intX As Integer = Screen.PrimaryScreen.Bounds.Width
        Dim intY As Integer = Screen.PrimaryScreen.Bounds.Height
        Return intX & " × " & intY
End Function

How to change current screen resolution — solution

Tags:

Vb.Net