I want to do this:
Const开发者_运维技巧 COLOR_GREEN = &H00FF00
Me.Label1.BackColor = COLOR_GREEN
There is a problem however in that vb automatically decides to convert &H00FF00 to &HFF00 so I get this instead:
Const COLOR_GREEN = &HFF00
Me.Label1.BackColor = COLOR_GREEN
The decimal value COLOR_GREEN is now -256 instead of 65280 and so the background is black instead of green! This is annoying as I can perfectly well set the color in form design mode using #00FF00.
What is the equivalent in vb of setting a color to #00FF00 in the form design mode?
Have you tried the literal &H0000FF00&
? The following code works just fine for me:
Const COLOR_GREEN = &H0000FF00&
Me.Label1.BackColor = COLOR_GREEN
Of course, VB 6 automatically collapses it to this, which still works just fine because the two values are completely equivalent numerically:
Const COLOR_GREEN = &HFF00&
Me.Label1.BackColor = COLOR_GREEN
The trick is that the value needs to be declared as a Long
, rather than an Integer
. Putting the ampersand (&
) after the numeric literal accomplishes this.
That also explains why you're seeing a value of -256 instead of the 65280 that you expect. The value 65280 is too long to fit in an Integer
, and when it overflows that data type, VB 6 wraps it around again, producing -256.
It's also worth noting that hexadecimal literals in VB 6 will not be equivalent to those that you are probably familiar with from the web and HTML programming. Instead of the RRGGBB notation that you find there, VB 6 uses BBGGRR notation, or &H00BBGGRR&
, the same as the native Win32 COLORREF
structure where the low-order byte is red, rather than blue.
Of course, do note that for standard color values like the one you've shown here, you're probably better off using the VB literals, such as vbGreen
:
Me.Label1.BackColor = vbGreen
You cannot preserve the leading zeros in vb's hex notation.
Numeric literals (inclding &H*
) default to 16bit integers, for a 32bit constant literal suffix with &
to implicitly state its a long;
Const COLOR_GREEN = &HFF00&
?COLOR_GREEN
65280
You can use Colortranslator
dim myColor as new Color
myColor=ColorTranslator.fromHTML("#ff0000") 'Red color
精彩评论