Using a union to retrieve the RGB components of a color

In VB.NET you can create what in C is called a union, i.e. a particular structure where you can access the same memory with different names. Here’s how you declare such a structure by using the StructLayout attribute, and specifying that you want to define the structure layout explicitly, namely how the fields will be saved in memory within the type.

 Structure ARGBColor   Dim Red As Byte   Dim Green As Byte   Dim Blue As Byte   Dim Alpha As Byte   Dim Value As IntegerEnd Structure

If you set the Value field, you’re actually setting all the 4 bytes of the structure in a single step. Otherwise you can get and set the single bytes of the structure with the other fields. Here’s how you can set the Value field of a variable of type ARGBColor to an hexadecimal value that represents a color, and then read the other fields to retrieve its RGB components:

' Split a color into its components.Dim rgb As ARGBColorrgb.Value = &H112233         ' This is equal to 1122867.Console.WriteLine(String.Format("Red={0}, Green={1}, Blue={2}", rgb.Red, _    rgb.Green, rgb.Blue))    ' => Red=51, Green=34, Blue=17

————————–
Note: this code is taken from Francesco Balena’s Programming Microsoft Visual Basic .NET book (MS Press 2002)

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a