Is there a way in VB.NET to have buttons and menu bars that are built in the code show up in the design view? - vb.net

Is there a way in VB.NET to make components like buttons and menus bars show in design view of you added them in programmatically?
I now in Java i you add a button in the code it will show in design view if you switch back and forth. Can this be done in VB.NET.
Code:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'defining the main menu bar
Dim mnuBar As New MainMenu()
'defining the menu items for the main menu bar
Dim myMenuItemFile As New MenuItem("&File")
Dim myMenuItemEdit As New MenuItem("&Edit")
Dim myMenuItemView As New MenuItem("&View")
Dim myMenuItemProject As New MenuItem("&Project")
'adding the menu items to the main menu bar
mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)
' defining some sub menus
Dim myMenuItemNew As New MenuItem("&New")
Dim myMenuItemOpen As New MenuItem("&Open")
Dim myMenuItemSave As New MenuItem("&Save")
'add sub menus to the File menu
myMenuItemFile.MenuItems.Add(myMenuItemNew)
myMenuItemFile.MenuItems.Add(myMenuItemOpen)
myMenuItemFile.MenuItems.Add(myMenuItemSave)
'add the main menu to the form
Me.Menu = mnuBar
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
'create a new TreeView
Dim TreeView1 As TreeView
TreeView1 = New TreeView()
TreeView1.Location = New Point(5, 30)
TreeView1.Size = New Size(150, 150)
Me.Controls.Add(TreeView1)
TreeView1.Nodes.Clear()
'Creating the root node
Dim root = New TreeNode("Application")
TreeView1.Nodes.Add(root)
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 1"))
'Creating child nodes under the first child
For loopindex As Integer = 1 To 4
TreeView1.Nodes(0).Nodes(0).Nodes.Add(New _
TreeNode("Sub Project" & Str(loopindex)))
Next loopindex
' creating child nodes under the root
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 6"))
'creating child nodes under the created child node
For loopindex As Integer = 1 To 3
TreeView1.Nodes(0).Nodes(1).Nodes.Add(New _
TreeNode("Project File" & Str(loopindex)))
Next loopindex
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Private Sub openInWeb()
Try
Dim url As String = "http://www.stackoverflow.com"
Process.Start(url)
Catch ex As Exception
MsgBox("There's something wrong!")
Finally
End Try
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fileReader As System.IO.StreamReader
fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\Users\itpr13266\Desktop\Asnreiu3.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)
openInWeb()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim myStream As Stream = Nothing
Dim openFileBox As New OpenFileDialog()
openFileBox.InitialDirectory = "c:\"
openFileBox.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileBox.FilterIndex = 2
openFileBox.RestoreDirectory = True
If openFileBox.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileBox.OpenFile()
If (myStream IsNot Nothing) Then
' Insert code to read the stream here.
'**************************
' your code will go here *
'**************************
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
myStream.Close()
End If
End If
End Sub
Private Sub ToolTip1_Popup(sender As System.Object, e As System.Windows.Forms.PopupEventArgs) Handles ToolTip1.Popup
End Sub
Private Sub Button(p1 As Object)
Throw New NotImplementedException
End Sub
Private Function myButton() As Windows.Forms.Button
Throw New NotImplementedException
End Function
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
AboutBox1.Show()
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Dim lbl As New Label
lbl.Size = New System.Drawing.Size(159, 23) 'set your size (if required)
lbl.Location = New System.Drawing.Point(12, 190) 'set your location
lbl.Text = "You just clicked button 5" 'set the text for your label
Me.Controls.Add(lbl) 'add your new control to your forms control collection
End Sub
Public Sub HellowWorld()
MsgBox("Hello World!")
End Sub
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
HellowWorld()
End Sub
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
Dim ProgressBar1 As ProgressBar
Dim ProgressBar2 As ProgressBar
ProgressBar1 = New ProgressBar()
ProgressBar2 = New ProgressBar()
'set position
ProgressBar1.Location = New Point(10, 200)
ProgressBar2.Location = New Point(10, 250)
'set values
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 200
ProgressBar1.Value = 130
ProgressBar2.Minimum = 0
ProgressBar2.Maximum = 100
ProgressBar2.Value = 40
'add the progress bar to the form
Me.Controls.Add(ProgressBar1)
Me.Controls.Add(ProgressBar2)
' Set the caption bar text of the form.
End Sub
End Class

The Designer does only show Controls that are created in the FormName.Designer.vb file. It does not run code in the FormName.vb file. When adding controls in the Designer, they are added to the InitializeComponent() method in the FormName.Designer.vb file.
So the only way to show the controls in the Designer is to add them in the Designer or to edit the FormName.Designer.vb file manually. If you decide for the latter, you should mimic the code that is generated by the Designer very closely in order to avoid problems when the Designer is shown. Also, be prepared that the Designer regards the FormName.Designer.vb file as completely generated code and might decide to recreate the file sooner or later omitting parts that it cannot handle.
Side note: in order to see the FormName.Designer.vb file, you should select "Show All Files" for the project in Solution Explorer.

Related

How do I get a value from a dynamic control?

I've got a form with a picturecontrol (default to black bg) and I have a flowlayoutpanel underneath. On the form's load it cycles through a folder of images and creates a thumbnail (picturecontrol) inside the flowlayoutpanel. What I want to do is dynamically add a click event to let the user change the main picturecontrol image with one of the thumbnails.
Private Sub TabImageLoad()
Dim apppath As String = Application.StartupPath()
Dim strFileSize As String = ""
Dim di As New IO.DirectoryInfo(apppath + "\images")
Dim aryFi As IO.FileInfo() = di.GetFiles("*.*")
Dim fi As IO.FileInfo
For Each fi In aryFi
If fi.Extension = ".jpg" Or fi.Extension = ".jpeg" Or fi.Extension = ".gif" Or fi.Extension = ".bmp" Then
Dim temp As New PictureBox
temp.Image = Image.FromFile(di.ToString + "\" + fi.ToString)
temp.Width = 100
temp.Height = 75
temp.Name = fi.ToString
temp.Visible = True
temp.SizeMode = PictureBoxSizeMode.StretchImage
AddHandler temp.Click, AddressOf Me.temp_click
FlowLayoutPanel1.Controls.Add(temp)
End If
Next
End Sub
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
PictureBox1.Image = temp.Image
End Sub
This is my code for the sub that gets the images (note the addhandler attempt) and the sub that links to the addhandler. As you've probably guessed the addhandler doesn't work because "temp" is not declared in the temp_click sub.
Any suggestions?
The sender argument is always the control that triggered the event, in this case a PictureBox:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pb As PictureBox = DirectCast(sender, PictureBox)
PictureBox1.Image = pb.Image
End Sub
I suggest you to use:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pbDynamic as PictureBox = trycast(sender,Picturebox)
Then validate with
if pbDynamic IsNot Nothing Then
PictureBox1.Image = pbDynamic.image
end if
This way you avoid runtime errors and null pointer exceptions

hiding process icon to run in background

I have a programs path..like utorrent and it pid too. I have achieved these values programatically using vb.net. I just want to hide their icon form tray just to run them in background and if possible attach the process with a hotkey to call them back. Is there any way to achieve this.
Option Strict On
Option Explicit On
Option Infer Off
Imports TrayHelper
Public Class Form1
Dim x1, y1 As Single
Friend WithEvents lv As New ListView With {.Parent = Me, .Dock = DockStyle.Fill}
Private il As New ImageList
Dim nxt As Integer
Friend WithEvents mnuContextMenu As New ContextMenu() 'Moved this to be declared as global
Dim mnuItemHide As New MenuItem()
Dim mnuItemExit As New MenuItem()
Dim things As List(Of TrayButton) = TrayHelper.Tray.GetTrayButtons()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Controls.Add(lv)
lv.View = View.Details
il.ColorDepth = ColorDepth.Depth32Bit
lv.SmallImageList = il
lv.Columns.Add("Button Text", 300, HorizontalAlignment.Left)
lv.Columns.Add("PID", 50, HorizontalAlignment.Left)
lv.Columns.Add("Process Path", 600, HorizontalAlignment.Left)
'Dim things As List(Of TrayButton) = TrayHelper.Tray.GetTrayButtons()
For Each b As TrayButton In things
If b.Icon IsNot Nothing Then
il.Images.Add(b.TrayIndex.ToString, b.Icon)
Else
' When we can't find an icon, the listview will display this form's one.
' You could try to grab the icon from the process path I suppose.
il.Images.Add(b.TrayIndex.ToString, Me.Icon)
End If
Dim lvi As New ListViewItem(b.Text)
lvi.SubItems.Add(b.ProcessIdentifier.ToString)
lvi.SubItems.Add(b.ProcessPath)
lvi.ImageKey = b.TrayIndex.ToString
lv.Items.Add(lvi)
Next
lv.MultiSelect = False
'lv.ContextMenu = mnuContextMenu 'Don`t need to add if done this way
lv.FullRowSelect = True 'Added this but, you don`t need it if you don`t want it
mnuItemHide.Text = "&Hide"
mnuItemExit.Text = "&Exit"
mnuContextMenu.MenuItems.Add(mnuItemHide)
mnuContextMenu.MenuItems.Add(mnuItemExit)
AddHandler mnuItemHide.Click, AddressOf Me.menuItem1_Click
End Sub
Private Sub lv_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lv.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
If lv.GetItemAt(e.X, e.Y) IsNot Nothing Then
lv.GetItemAt(e.X, e.Y).Selected = True
mnuContextMenu.Show(lv, New Point(e.X, e.Y))
mnuItemExit.Visible = True
mnuItemHide.Visible = True
End If
End If
End Sub
Private Sub menuItem1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txtValue as String
txtValue = lv.FocusedItem.SubItems(2).Text
Kill(txtValue)
Dim txtValue1 As String
txtValue1 = lv.FocusedItem.SubItems(0).Text
MessageBox.Show(txtValue1 + " has been hidden")
End Sub
End Class
this is my code
To hide your form -> form1.visible=false
To hide your form from taskbar -> form1.ShowinTaskbar=false
then go to the form1 keydown event and put this...
If e.Control And e.KeyCode = Keys.Q Then ' ---> activate with Ctrl-Q
form1.visible=true
End If

Save Data to text tile using SaveFileDialog?

I have already viewed the MSDN Example but I am still having problems.
I created a super-simple program to multiply two numbers, and display the output in the textbox. Now I need to be able to read that text box value and put the value in a text file, bringing up the save to file dialog when the "Save To File" button is clicked.
Private Sub MutiplyBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MutiplyBtn.Click
Dim FirstNum As Double = Num1.Text
Dim SecondNum As Double = Num2.Text
Dim Answer2 As Double = FirstNum * SecondNum
Answerbox.Text = Answer2
End Sub
Private Sub SaveResultToFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveResultToFile.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
System.IO.File.WriteAllText(Answerbox.Text)
myStream.Close()
End If
End If
End Sub
Currently, Visual Studio is giving me an error: Overload resolution failed because no accessible 'WriteAllText' accepts this number of arguments.
WriteAllText static method requires the name of the file where the data should be written to.
You could use directly the name selected in the saveFileDialog1
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
System.IO.File.WriteAllText(saveFiledialog1.FileName, Answerbox.Text)
End If
instead if you really want to use the stream opened by OpenFile() method your code should be
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Dim sw As StreamWriter = new StreamWriter(saveFileDialog1.OpenFile())
If (sw IsNot Nothing) Then
sw.WriteLine(Answerbox.Text)
sw.Close()
End If
End If
The code is an example, you need to add a bit of error handling
Hi I tried above method but I succeed in this way....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _
Then
My.Computer.FileSystem.WriteAllText _
(SaveFileDialog1.FileName, RichTextBox1.Text, True)
End If
End Sub

How to append text pending on checkbox state?

I’m making a form with a checkbox where if checked a target file is appended with text-A and if Unchecked the file is appended with text-B
How can I do this?
what i have sofar:
Private Sub CheckBox1_Checked(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.Checked
Dim FILE_NAME As String = "C:\ANSWERSLIST.txt"
'Adding items for AutoCAD 2006...
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine("YES")
objWriter.Close()
End If
End Sub
You could use the AppendAllText method:
If MyCheckBox.IsChecked Then
File.AppendAllText("foo.txt", "text-A")
Else
File.AppendAllText("foo.txt", "text-B")
End If

Read Text File and Output Multiple Lines to a Textbox

I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub