Setting a windows form's screen position based on another form's current position - vb.net

I am creating an application with multiple windows forms. The main form is movable, and I want a confirmation window to flash based on where the main form is located.
For example, the main form opens, user drags it 200 points to the left. How do I make sure the confirmation window, upon button-press, opens up exactly to the left of that window?
The built-in properties (center screen, center parent, etc.) don't provide this functionality.
I'm aware of these functions:
Form1.Left += 200
and
Dim frmAccounts as new Form()
Set FrmAccounts.DesktopLocation = new Point(100,100)
but neither of these take into consideration user dragging.
Any ideas?
Thanks for your help.

To keep the buddy glued to the main form, you have to use the main form's LocationChanged event to know when to move it. And you have to position it before it is displayed, that's a bit tricky due the form possibly getting rescaled on a machine with a different DPI setting. Best time to do it is when the buddy's Load event fires, it is rescaled by then. Some sample code:
Public Class Form1
Dim buddy As Form
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If buddy Is Nothing Then
buddy = New Form2
AddHandler buddy.Load, AddressOf MoveBuddy
AddHandler Me.LocationChanged, AddressOf MoveBuddy
AddHandler buddy.FormClosed, Sub() buddy = Nothing
buddy.Show(Me)
End If
End Sub
Private Sub MoveBuddy(sender As Object, e As EventArgs)
buddy.Bounds = New Rectangle(Me.Left - buddy.Width, Me.Top, buddy.Width, buddy.Height)
End Sub
End Class

Related

Most efficient way to programmatically update and configure forms and controls

I am looking for a way to prevent user form controls from appearing one by one when I'm programmatically adding them and for ways to enhance application performance and visual appeal.
Say, I have a Panel_Top in which I programmatically add comboboxes. What is happening is that they appear one by one as they are created and I am looking for a way to suspend the refreshing of the panel and or user form to make all of those programmatically added comboboxes to appear at the same time and faster than it happens right now.
I've tried suspendlayout which doesn't do anything for me or maybe I'm doing it wrong.
MyForm.PanelTop.SuspendLayout = true
And also I've tried to set the Panel_Top to invisible like:
MyForm.Top_Panel.visible = false
Which kind of sorta looks and performs better, or it might be a placebo.
What is the correct approach to this problem?
PS: I do have form set to doublebuffer = true, if that matters
What I tend to do is create a loading modal to appear on top of the form rendering the controls that need to be created/made visible, this can optionally have a progress bar that gets incremented as the control is created/shown. With the loading modal running, the container that needs to add the controls starts with SuspendLayout, adds the controls, and then finished with ResumeLayout.
This makes it so that controls are added/shown while giving the user a visual indicator that something is going on behind the scenes.
Here is a phenomenal example of a loading modal: https://www.vbforums.com/showthread.php?869567-Modal-Wait-Dialogue-with-BackgroundWorker and here is an example of using it:
Private ReadOnly _controlsToAdd As New List(Of Control)()
Private Sub MyForm_Show(sender As Object, e As EventArgs) Handles MyBase.Shown
Using waitModal = New BackgroundWorkerForm(AddressOf backgroundWorker_DoWork,
AddressOf backgroundWorker_ProgressChanged,
AddressOf backgroundWorker_RunWorkerCompleted)
waitModal.ShowDialog()
End Using
End Sub
Private Sub backgroundWorker_DoWork(sender As Object, e As DoWorkEventArgs)
Dim worker = DirectCast(sender, BackgroundWorker)
For index = 1 To 100
_controlsToAdd.Add(New ComboBox() With {.Name = $"ComboBox{index}"})
worker.ReportProgress(index)
Threading.Thread.Sleep(100) ' Zzz to simulate a long running process
Next
End Sub
Private Sub backgroundWorker_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
Dim percentageCompleted = e.ProgressPercentage / 100
' do something with the percentageCompleted value
End Sub
Private Sub backgroundWorker_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
PanelTop.SuspendLayout()
PanelTop.Controls.AddRange(_controlsToAdd.ToArray())
PanelTop.ResumeLayout()
End Sub
SuspendLayout() is the correct way to handle this with WinForms.
But first of all, this is a function you call, and not a flag you set.
Secondly, don't forget to call ResumeLayout() at the end of the changes.
Finally, you need to ensure you only call them once when you start to change around the controls in the panel and then again at the very end. If you use them with every control you won't get any benefit.
So the pattern might look something like this:
Public Sub SomeMethod()
PanelTop.SuspendLayout() ' Prevent the panel from updating until you've finished
' Make a bunch of changes
PanelTop.Controls.Clear()
For Each ...
PanelTop.Controls.Add( ... )
Next
PanelTop.ResumeLayout() ' Allow the panel to show all the changes in the same WM_PAINT event
End Sub
You also need to ensure you don't have anything in there like DoEvents()/Invalidate() that might invoke the windows message loop and cause the form to redraw itself.

How do I make controls inside of a FlowLayoutPanel do things?

I'm adding controls to a FlowLayoutPanel like this:
Dim box As New PictureBox
(I'm making the controls using code, then I'm using FlowPanelLayout1.Controls.Add(box)).
How do I make these controls do things? In my code I'm using For Each, so multiple are made using this, my goal is to make each one be able to do what I want and the code for each would be different. How can I achieve this goal?
I believe what you're after is AddHandler. AddHandler allows you to programmatically assign code to an event at runtime. So you can create a Sub specifically to handle events from the picture boxes you create.
You can also retrieve the control that raised the event. This allows you to modify it, or access it's tag, allowing you to attach data to the PictureBox when you add it to the FlowLayoutPanel.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Create a new picturebox
Dim PB As New PictureBox With {.Size = New Drawing.Size(50, 50), .SizeMode = PictureBoxSizeMode.Normal}
PB.Image = Image.FromFile("res.png")
'Add it to the FlowLayoutPanel
FlowLayoutPanel1.Controls.Add(PB)
'Assign HandlePictureboxClick() to handle the PictureBox's DoubleClick event.
AddHandler PB.DoubleClick, AddressOf HandlePictureboxClick
End Sub
Public Sub HandlePictureboxClick(sender As Object, e As EventArgs)
'Retrive the control that raised the event (In this case, the one you double-clicked)
Dim Picturebox As PictureBox = CType(sender, PictureBox)
'Do whatever you want to do with it
Picturebox.SizeMode = PictureBoxSizeMode.Zoom
End Sub
The example above will change the PictureBox's size mode to zoom when the user double clicks on it, without modifying the other PictureBoxes in the FlowLayoutPanel

How to remove the most recently added control?

I Intended to display an PictureBox in my form when the mouse hovered over another control. I then wanted to use a separate event for when the mouse left the control. This event would remove the displayed PictureBox from controls. However, because my events are private subs, I can't directly access the name of the control in the latter event. A solution to this would be a method that removes the most recently added control. If no such method exists, or there is an alternative way of approaching this problem, any help would be appreciated.
I tried simply using Controls.Remove(), but this requires a parameter. The name of the control as a string did not work either, as the parameter must be a control itself.
Private Sub Tile_MouseEnter(Sender As Object, e As EventArgs)
Dim CloseUpPic As New PictureBox With {Properties}
CloseUpPic.Image = Sender.Image
Controls.Add(CloseUpPic)
Refresh()
End Sub
Private Sub Tile_MouseLeave(Sender As Object, e As EventArgs)
Me.Controls.Remove()
End Sub
The program won't compile due to .Remove() needing a parameter
I expected for the Control to be created and displayed when the mouse entered the tile, and to cease to exist when the mouse left the tile.
For future reference, controls have Tag property which allows you to store whatever you like. In this case, you can store a reference to the newly created PictureBox. Furthermore, the "Sender" parameter tells you which control was the source of the event. You can cast sender to a control, then store the reference. Then, in the leave event, you can cast sender to a control, cast the .Tag to a control, and finally remove it:
Private Sub Tile_MouseEnter(Sender As Object, e As EventArgs)
Dim ctl As Control = DirectCast(Sender, Control)
Dim CloseUpPic As New PictureBox With {Properties}
CloseUpPic.Image = Sender.Image
Controls.Add(CloseUpPic)
ctl.Tag = CloseUpPic
Refresh()
End Sub
Private Sub Tile_MouseLeave(Sender As Object, e As EventArgs)
Dim ctl As Control = DirectCast(Sender, Control)
Dim ctlToRemove As Control = DirectCast(ctl.Tag, Control)
Me.Controls.Remove(ctlToRemove)
End Sub
I ended up using the following code to solve my issue:
For Each Closeup In Controls.OfType(Of CloseUp)
Controls.Remove(Closeup)
Next
I created a new class of my own called Closeup, that inherits PictureBox. I then looped through each Closeup in controls (There was only one but this code works for multiple controls), and removed them.

How to dispose of a form within a panel upon closing the main form or upon another button click event?

Disclaimer: I only have beginner to slightly intermediate experience with VB.net
Hello, I was tinkering around with some design ideas for a project and I ran into a problem that I haven't found a solution to. I have a win form with some buttons and a panel. When the user presses a button, a border-less form is loaded into the panel. The problem is this: when the main form is closed, Visual Studio does not stop debugging, presumably because the forms in the panel are not disposed of.
Win Form image
The instance of the panel form is declared in the button click event. How can I destroy that instance from another sub? If I click another button, the first panel form doesn't go away. Is there a better way to accomplish this? I'm still learning, so I'm often not aware of all the different ways to solve a problem. Thanks everyone!
Public Class frm_Clients
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim search As New Search
search.TopLevel = False
search.Dock = DockStyle.Fill
Panel1.Controls.Add(search)
search.Show()
End Sub
Private Sub frm_Clients_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
' What should I write here?
End Sub
End Class
Here's a snippet of what to do to close the windows when another button is pressed.
For Each form In Panel1.Controls.OfType(Of Form).ToList()
form.Close()
Next
Then I would suggest that you set search.Owner to the Form holding the Panel. That means that when the Owner is closed, so are the children.
search.Owner = Me

page turning animation

I am building an application. This shows a form, header and footer are to be kept fixed.
In the middle there is a Group Box that hold a question with different option.
When user clicks Next button at the bottom, Group Box loads next question.
I want to make this change animated. I wish to show a page-turning animation that runs when Next button is clicked...................
Please help
Thanks
Furqan
There is a very nicely written tutorial for doing this in C# and GDI but it's fairly complicated.
There is also a simpler tutorial, also on CodeProject, for doing this with Silverlight.
How to create a Loading screen in VB.Net
To create a loading screen you need to understand the ‘BackgroundWorker’ which is part of the Imports System.ComponentModel
Create a Loading form with your loading message and picture. This form will act as a popup form
I called my form ‘frmPleaseWait’ and placed the following code in it
Public Class frmPleaseWait
Private _worker As BackgroundWorker
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
_worker = New BackgroundWorker()
AddHandler _worker.DoWork, AddressOf WorkerDoWork
AddHandler _worker.RunWorkerCompleted, AddressOf WorkerCompleted
_worker.RunWorkerAsync()
End Sub
Private Sub WorkerDoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
Threading.Thread.Sleep(5000)
'your loading animation code goes here
End Sub
Private Sub WorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
Me.DialogResult = Windows.Forms.DialogResult.OK
Me.Close()
End Sub
End Class
In your main form in between the code that’s taking the processing time place
Dim frm As New frmPleaseWait
frm.ShowDialog()
'your time consuming main processing code goes here
frm.Close()
That’s all, if you want to make the popup form appear longer then change the threading time in WorkerDoWork method.
#Furqan, in your case, in this section you need to put your animation code in the WorkerDoWork method
Dont forget to use Imports System.ComponentModel at the top of the loading form class
Thanks Eddy Jawed