How to make transparent label in vb.net? [duplicate] - vb.net

This question already has answers here:
Transparent control over PictureBox
(8 answers)
Closed 4 years ago.
I have a label which is on a picture. So I want to make transparent back color of the label. When I make backcolor property of the label to transparent. The picture doesn't showed through the text box back color. The backcolor gets color of the form.
Image

The background of a Lable is inherited from its container Background.
You can set a different Parent Container using the [Control].Controls.Add() method, which sets the Parent property to the new Container (you could also modify the .Parent property directly).
You can re-define your Label's Parent in the Form constructor (the Public Sub New() of a Form - insert the code after InitializeComponent()) or in the Form.Load() event handler.
Here I'm showing both, pick one:
Public Sub New()
InitializeComponent()
PictureBox1.Controls.Add(Label1)
'Re-define the Label.Location if required
Label1.Location = New Point(0, 0)
End Sub
The same thing in the Form.Load() event:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PictureBox1.Controls.Add(Label1)
End Sub
As an alternative, you could use the PictureBox .Paint() event's e.Graphics to simply Draw the same Text.
Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
Using TextBrush As SolidBrush = New SolidBrush(Me.ForeColor)
e.Graphics.DrawString("BITS Registration ID", Me.Font, TextBrush, New Point(5, 5))
End Using
End Sub

Related

How can I apply a MouseHover and MouseLeave to two controls to act as one control?

I have two labels in my form which are placed side-by-side to act as one label. When I hover over the labels, I have a function that fades the labels to different colours, which works well. I am trying to apply the MouseHover and MouseLeave event to both labels, so that when I hover over Label1 and move to Label2 (and vice versa), the function doesn't then fade the colour back to the original colour. Currently, moving between the two labels activates MouseLeave followed by MouseHover again in the new label.
I have tried to add both labels to the event trigger, but this hasn't worked. I have also tried placing both labels in a Panel, but that then doesn't trigger the event.
Private Sub fadeHeaderIn(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Label1.MouseHover, Label2.MouseHover
Call fadeLabel("In")
End Sub
Private Sub fadeHeaderOut(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Label1.MouseLeave, Label2.MouseLeave
Call fadeLabel("Out")
End Sub
If the functionality to change the colour of part of the label existed, I'd not need the two labels, so if there is a better way of doing this altogether, I'm happy to do so. Thanks!
I have also tried placing both labels in a Panel, but that then
doesn't trigger the event.
That should work. The panel would act as the boundaries for both labels. You'll get a MouseLeave, though, when you move from the panel to the labels contained within. To prevent a false trigger, simply check if the mouse is still within the bounds of the panel. You can prevent multiple fade ins when moving from label to label by tracking the faded state with a boolean. It'd look something like this:
Public Faded As Boolean = False
Private Sub fadeHeaderIn(sender As Object, e As EventArgs) Handles Label1.MouseHover, Label2.MouseHover
If Not Faded Then
Faded = True
fadeLabel("In")
End If
End Sub
Private Sub fadeHeaderOut(sender As Object, e As EventArgs) Handles Panel1.MouseLeave
If Not Panel1.ClientRectangle.Contains(Panel1.PointToClient(Cursor.Position)) Then
If Faded Then
Faded = False
fadeLabel("Out")
End If
End If
End Sub
Here's a sample of what has been described in comments.
The Text of a control (here, derived from a standard Label) is split in two sections of the same measure. Each section can have a different color.
The active and inactive colors are custom public properties, they can be set in the designer.
Each section is tracked, meaning that the control is aware of what side the Mouse Pointer is currently hovering.
The size of the text is measured using the TextRenderer.MeasureText method. This size is used to calculate the rectangles that include the sections of text.
The Rectangle.Contains([Point]) method is then used to determine which section of the text the mouse pointer in hovering. [Point] is calculated using the MousePosition property, translated to client coordinates using the Control.PointToClient() method.
When the mouse pointer is moved from one section of text to the other (here, just two sections, more could be defined adding more rectangles), the control is Invalidated, causing a call to the OnPaint method of the control.
If the mouse pointer is not hovering a section of text, base.OnPaint(e) is called (also causing the Paint event to raise), which draws the default text with the default color.
In the OnPaint method, the Graphics region is clipped using the Rectangles that define the text sections. A subsequent call to TextRenderer.DrawText, setting the TextFormatFlags.PreserveGraphicsClipping flag, clips the text in the defined region, so just the section of text that fits in the clipping region is painted.
The Graphics.ExcludeClip() method is used here to define these clipping regions.
The TextFormatFlags.ExternalLeading and TextFormatFlags.TextBoxControl are also used to replicate the default text rendering, so the custom text is rendered in the same relative position.
This is how it behaves:
Custom Control Class to test the functionality:
Imports System.ComponentModel
Imports System.Drawing
Imports System.Windows.Forms
<DesignerCategory("Code")>
Public Class LabelSplitText
Inherits Label
Private m_Text As String = String.Empty
Private m_Sections As RectangleF() = Nothing
Private m_PaintText As Boolean = False
ReadOnly flags As TextFormatFlags = TextFormatFlags.ExternalLeading Or
TextFormatFlags.PreserveGraphicsClipping Or
TextFormatFlags.TextBoxControl
Public Sub New()
InitializeComponent()
End Sub
Private Sub InitializeComponent()
ResizeRedraw = True
End Sub
Public ReadOnly Property ActiveRectangle As RectangleF
Public ReadOnly Property ActiveSide As String = String.Empty
Public Property ActiveColor As Color = Color.White
Public Property InactiveColor As Color = Color.DimGray
Protected Overrides Sub OnLayout(e As LayoutEventArgs)
MyBase.OnLayout(e)
Me.AutoSize = False
m_Text = Me.Text
End Sub
Protected Overrides Sub OnMouseEnter(e As EventArgs)
m_Text = Me.Text
Text = String.Empty
m_PaintText = True
MyBase.OnMouseEnter(e)
Invalidate()
End Sub
Protected Overrides Sub OnMouseLeave(e As EventArgs)
m_PaintText = False
Me.Text = m_Text
MyBase.OnMouseLeave(e)
End Sub
Protected Overrides Sub OnMouseMove(e As MouseEventArgs)
MyBase.OnMouseMove(e)
Invalidate()
If m_Sections Is Nothing Then Return
Me._ActiveRectangle = If(m_Sections(0).Contains(e.Location), m_Sections(0), m_Sections(1))
End Sub
Protected Overrides Sub OnMouseClick(e As MouseEventArgs)
Me._ActiveSide = If(m_Sections(0).Contains(e.Location), "left", "right")
MyBase.OnMouseClick(e)
End Sub
Protected Overrides Sub OnPaint(e As PaintEventArgs)
If Not m_PaintText Then
MyBase.OnPaint(e)
Return
End If
Dim textSize As SizeF = TextRenderer.MeasureText(e.Graphics, m_Text, Me.Font, Me.ClientSize, flags)
m_Sections = GetTextAreaSections(textSize)
e.Graphics.ExcludeClip(Rectangle.Round(m_Sections(1)))
TextRenderer.DrawText(e.Graphics, m_Text, Me.Font, Point.Empty, GetSectionColor(0), flags)
e.Graphics.ResetClip()
e.Graphics.ExcludeClip(Rectangle.Round(m_Sections(0)))
TextRenderer.DrawText(e.Graphics, m_Text, Me.Font, Point.Empty, GetSectionColor(1), flags)
End Sub
Private Function GetSectionColor(section As Integer) As Color
Return If(m_Sections(section).Contains(PointToClient(MousePosition)),
Me.ActiveColor, Me.InactiveColor)
End Function
Private Function GetTextAreaSections(textSize As SizeF) As RectangleF()
If textSize.Width > Me.ClientSize.Width Then textSize.Width = Me.ClientSize.Width
Dim rectLeft = New RectangleF(PointF.Empty,
New SizeF(textSize.Width / 2.0F, Me.ClientSize.Height))
Dim rectRight = New RectangleF(New PointF(textSize.Width / 2.0F, 0),
New SizeF(textSize.Width / 2.0F, Me.ClientSize.Height))
Return {rectLeft, rectRight}
End Function
End Class

Panel edge detection, stop before going out of bounds

I have a panel inside it's parent panel that I allow to move. I want it to stop moving BEFORE it falls out of the parent panel. What is the best way to accomplish this. Also I add the panels dynamically.
UPDATE:
Here is the code that goes into the "MyPanel" Panel. Only difference between "MyPanel" vs "Panel" is I add a border and the ability to move it. The "CoolMove" was from another person's answer I found online. I add a "MyPanel1" to form and then add another "MyPanel2" to that and allow it to move only if it is on the "MyPanel1". So with that, I want "MyPanel2" to stay completely in bounds of "MyPanel1". I'm struggling to get the right code to accomplish this.
Private allowCoolMove As Boolean = False
Private myCoolPoint As New Point
Public Overridable Sub MyPanel_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
'If panel is ontop of Stock panel, then allow manual moving
If Me.Parent.Name.StartsWith("S") Then
allowCoolMove = True
myCoolPoint = New Point(e.X, e.Y)
Me.Cursor = Cursors.SizeAll
Me.BringToFront()
ElseIf Not Me.Parent.Name.Contains("keyR") Then
DoDragDrop(Me, DragDropEffects.Move)
End If
End Sub
Private Sub MyPanel_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
If allowCoolMove = True Then
Me.Location = New Point(Me.Location.X + e.X - myCoolPoint.X, Me.Location.Y + e.Y - myCoolPoint.Y)
End If
End Sub
Private Sub MyPanel_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp
allowCoolMove = False
Me.Cursor = Cursors.Default
End Sub
Each control has a ClientRectangle property that returns the dimensions of its client area (which, for a panel, is the interior part). There is also a DisplayRectangle property, which tells you the entire area of the control.
And the Rectangle structure has a Contains method overload that takes another Rectangle structure and tells you whether one rectangle is fully contained within the bounds of another rectangle.
You should be able to put those two facts together, now, to come up with code that will solve your problem. Something like:
Dim rcParentPanelInterior As Rectangle = parentPanel.ClientRectangle
Dim rcChildPanel As Rectangle = childPanel.DisplayRectangle
If rcParentPanelInterior.Contains(rcChildPanel)
' continue to allow moving
Else
' forbid moving
End If

Animate Picturebox in VB

I am new to VB and just can't figure it out how to animate a button using the MouseHover Event..
I want to create a single loop for all the buttons(picturebox) in my project that will increase the button's size when the user rests the mouse on it.
Maybe something like:
For Each Form As Form In Application.OpenForms
For Each Control As Control In Form.Controls
Tks. Any help is appreciated.
Use Inherits to create a new button (or PictureBox) class for you purpose. Here is the code.
Public Class cuteButton
Inherits System.Windows.Forms.Button
Protected Overrides Sub OnMouseHover(e As EventArgs)
'
'Wite code here to change button size or whatever.
'
MyBase.OnMouseHover(e)
End Sub
End Class
A very simple way is to use a common MouseHover event to grow your buttons (which I guess is really a Picturebox with an image in it):
Private Sub CustomButton_Grow(sender As Object, e As System.EventArgs) Handles Picturebox1.MouseHover, Picturebox2.MouseHover
'Set a maximum height to grow the buttons to.
'This can also be set for width depending on your needs!
Dim maxHeight as single = 50
If sender.Height < maxHeight then
sender.Size = New Size(sender.Width+1,sender.Height+1)
End if
End Sub
Then you can reset all buttons in a snap using the MouseLeave event. If you want that part animated as well then you can to use a global shrink routine that constantly shrink all buttons but the one in MouseHover. Good luck!
This Will Work even if you have 10,000 button or picture box ....
I am Assuming that you only have 1 form and many Buttons ,,, you have to be specific on your question
This Code will work fine with Buttons, Picturebox ,text box
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each cntrl As Control In Controls ' Looping for each Button as Control
If TypeOf cntrl Is Button Then
AddHandler cntrl.MouseEnter, AddressOf cntrl_MouseEnter ' Adding the event and handler
AddHandler cntrl.MouseLeave, AddressOf cntrl_MouseLeave ' Adding the event and handler
End If
Next
End Sub
'' Assuming you wanna eNlarge everytime the mouse Hover or Enter
Private Sub cntrl_MouseEnter(sender As Object, e As EventArgs)
CType(sender, Button).Size = New Point(CType(sender, Button).Size.Width + 50, CType(sender, Button).Size.Height + 50)
End Sub
'' Here it goes back normal size
Private Sub cntrl_MouseLeave(sender As Object, e As EventArgs)
CType(sender, Button).Size = New Point(CType(sender, Button).Size.Width - 50, CType(sender, Button).Size.Height - 50)
End Sub

Create control at runtime [duplicate]

This question already has answers here:
How to programmatically add controls to a form in VB.NET
(5 answers)
Closed 8 years ago.
I need to make a picturebox in VB.NET using code not the toolbox so it is not on my form just i draw it when I want it in code. Also No I don't want to use the: visible = false or true
I want to get a picturebox shown on a special position/x,y. Then I need it to execute a command once clicked. I am making a vb game and that is going to be pretty much the graphics layout.
If it may help i was pretty much thinking of it displaying a panel which is going to be made by using the draw features etc...
This code should help you to
Create a PictureBox programmatically
Position it on the form
Set an image
Add a click event handler
Add it to the form
Make a new WinForms project and paste this code. No need to add any controls
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
addPictureBoxToForm()
End Sub
Private Sub addPictureBoxToForm()
Dim pb As New PictureBox
pb.Location = New Point(0, 0)
pb.Image = Bitmap.FromFile("C:\test.png")
AddHandler pb.Click, AddressOf PictureBox_Click
Me.Controls.Add(pb)
End Sub
Private Sub PictureBox_Click(sender As Object, e As EventArgs)
MessageBox.Show("The picture box was clicked")
End Sub

Howto add a custom border to a FormBorderStyle=None - form?

I have a form with the property FormBorderStyle set to 'None' and with a custom bar on top side for dragging and buttons.
Now I'd like to give the form a border because it's a child form and the parent form has the same background color as the child, so it's hard to see the child form.
And no, I can't/won't change the background color.
Help
There is a way without a need to set a background image and/or fixed sized form. So this is the most proper and simple way I guess. Say you have a form named Form1, all you need to do is:
Private Sub Form1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle, Color.Black, ButtonBorderStyle.Solid)
End Sub
An alternative, if you want to use the default border provided by your Windows version:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.Sizable
Me.Text = ""
Me.ControlBox = False
End Sub
You can use the Visual Basic .NET Power Packs which you can download here. It has this Control called LineShape that you can put onto your border-less form's edges, like this one program that I am currently working on.
The north border is just a LineShape with a BorderWidth set to 60 and the other borders' BorderWidths are set to 10.
Maybe you can use a BackgroundImage transparent except in the borders.
You can use this on the form paint event:
ControlPaint.DrawBorder(e.Graphics, Me.ClientRectangle, Color.Black, ButtonBorderStyle.Solid)
This will draw the client border only, also if you are resizing the form, or maximizing the form use Me.Refresh() on form resize events so that the form redraws its borders.
After seeing the answer by theGD, I did the same thing for a TableLayouPanel on a form:
Private Sub TableLayoutPanel1_Paint(sender As Object, e As PaintEventArgs) Handles TableLayoutPanel1.Paint
ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle, Color.DarkOrange, ButtonBorderStyle.Solid)
End Sub