I want to change text font using font dialog in vb.net - winforms

Here is my code and I am able to add the text by defining some font properties but I want to add this using Font dialog.Can anyone help me regarding this issue.
Public Class Form1
Dim pic_font As New Font("Arial Black", 40, FontStyle.Regular, GraphicsUnit.Pixel)
Dim bm As Bitmap = New Bitmap(100, 100)
Dim strText As String = "Diver Dude"
Dim szText As New SizeF
Dim ptText As New Point(125, 125)
Dim ptsText() As PointF
Dim MovingOffset As PointF
Dim ptsTextPen As Pen = New Pen(Color.LightSteelBlue, 1)
Dim MouseMoving As Boolean
Dim MouseOver As Boolean
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
Me.SetStyle(ControlStyles.DoubleBuffer, True)
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
PictureBox1.Hide()
bm = Image.FromFile(Application.StartupPath & "\DivePic.bmp")
szText = Me.CreateGraphics.MeasureString(strText, pic_font)
SetptsText()
ptsTextPen.DashStyle = DashStyle.Dot
End Sub
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
'Check if the pointer is over the Text
If IsMouseOverText(e.X - 10, e.Y - 10) Then
MouseMoving = True
'Determine the upper left corner point from where the mouse was clicked
MovingOffset.X = e.X - ptText.X
MovingOffset.Y = e.Y - ptText.Y
Else
MouseMoving = False
End If
End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
'Check if the pointer is over the Text
If IsMouseOverText(e.X - 10, e.Y - 10) Then
If Not MouseOver Then
MouseOver = True
Me.Refresh()
End If
Else
If MouseOver Then
MouseOver = False
Me.Refresh()
End If
End If
If e.Button = Windows.Forms.MouseButtons.Left And MouseMoving Then
ptText.X = CInt(e.X - MovingOffset.X)
ptText.Y = CInt(e.Y - MovingOffset.Y)
Me.Refresh()
End If
End Sub
Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
MouseMoving = False
Me.Refresh()
End Sub
Public Function IsMouseOverText(ByVal X As Integer, ByVal Y As Integer) As Boolean
'Make a Graphics Path from the rotated ptsText.
Using gp As New GraphicsPath()
gp.AddPolygon(ptsText)
'Convert to Region.
Using TextRegion As New Region(gp)
'Is the point inside the region.
Return TextRegion.IsVisible(X, Y)
End Using
End Using
End Function
Dim tbm As Bitmap
Private Sub Form1_Paint(ByVal sender As Object, _
ByVal e As System.Windows.Forms.PaintEventArgs) _
Handles MyBase.Paint
tbm = CType(bm.Clone, Bitmap)
Dim g As Graphics = Graphics.FromImage(tbm)
Dim mx As Matrix = New Matrix
Dim gpathText As New GraphicsPath
Dim br As SolidBrush = New SolidBrush(Color.FromArgb(tbarTrans.Value, _
KryptonColorButton1.SelectedColor))
SetptsText()
'Smooth the Text
g.SmoothingMode = SmoothingMode.AntiAlias
'Make the GraphicsPath for the Text
Dim emsize As Single = Me.CreateGraphics.DpiY * pic_font.SizeInPoints / 72
gpathText.AddString(strText, pic_font.FontFamily, CInt(pic_font.Style), _
emsize, New RectangleF(ptText.X, ptText.Y, szText.Width, szText.Height), _
StringFormat.GenericDefault)
'Draw a copy of the image to the Graphics Object canvas
g.DrawImage(CType(bm.Clone, Bitmap), 0, 0)
'Rotate the Matrix at the center point
mx.RotateAt(tbarRotate.Value, _
New Point(ptText.X + (szText.Width / 2), ptText.Y + (szText.Height / 2)))
'Get the points for the rotated text bounds
mx.TransformPoints(ptsText)
'Transform the Graphics Object with the Matrix
g.Transform = mx
'Draw the Rotated Text
If chkAddOutline.Checked Then
Using pn As Pen = New Pen(Color.FromArgb(tbarTrans.Value, KryptonColorButton2.SelectedColor), 1)
g.DrawPath(pn, gpathText)
End Using
Else
g.FillPath(br, gpathText)
End If
If CheckBox2.Checked = True Then
Dim p As New Pen(Color.FromArgb(tbarTrans.Value, KryptonColorButton2.SelectedColor), 1)
'draw te hollow outlined text
g.DrawPath(p, gpathText)
'clear the path
gpathText.Reset()
Else
g.FillPath(br, gpathText)
End If
'Draw the box if the mouse is over the Text
If MouseOver Then
g.ResetTransform()
g.DrawPolygon(ptsTextPen, ptsText)
End If
'Draw the whole thing to the form
e.Graphics.DrawImage(tbm, 10, 10)
'tbm.Dispose()
g.Dispose()
mx.Dispose()
br.Dispose()
gpathText.Dispose()
End Sub
Private Sub TrackBar_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles tbarRotate.Scroll, tbarTrans.Scroll
lblRotate.Text = tbarRotate.Value
lblOpacity.Text = tbarTrans.Value
Me.Refresh()
End Sub
Sub SetptsText()
'Create a point array of the Text Rectangle
ptsText = New PointF() { _
ptText, _
New Point(CInt(ptText.X + szText.Width), ptText.Y), _
New Point(CInt(ptText.X + szText.Width), CInt(ptText.Y + szText.Height)), _
New Point(ptText.X, CInt(ptText.Y + szText.Height)) _
}
End Sub
Private Sub chkAddOutline_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkAddOutline.CheckedChanged
Me.Refresh()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If FontDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
bm = Image.FromFile(OpenFileDialog1.FileName)
szText = Me.CreateGraphics.MeasureString(strText, pic_font)
SetptsText()
ptsTextPen.DashStyle = DashStyle.Dot
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
tbm.Save(SaveFileDialog1.FileName)
End If
End Sub
End Class

What do you mean.If you mean open a font dialog and select a font from it,here is the code.
' You need Import System.Drawing before your class
' In your class vars section
Dim fd As New FontDialog
'later in your code
' This should be in the code where you call the font dialog
If(fd.ShowDialog() == DialogResults.Ok)
pic_font = fd.Font
End If

Related

argument out of range parameter name index

since i have the code of the auto generated text box
Insert data from auto generated textbox to SQL Server database
i am try to write a code for ensuring of the auto generated text box in FlowLayoutPanel1 contain data
the auto generated text box build depends on the number in Val(Label2.Text) of the real part
and if any text box is null or empty then the process will stop until fill all fields
the auto generated text box will be like this if the Val(Label2.Text)
is equal to 3
so i try this in the save button
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
so i getting error after leave some text box and back to fill it again
and the all of form code is
Imports System.Data.SqlClient
'library for create folders
Imports System.IO
Public Class part
Dim cLeft As Integer = 1
Dim top1 As Integer = 5
Dim i As Integer = 0
Dim path1 As String
Dim cmd As SqlCommand
Public Sub AddNewTextBox()
Dim txt As New System.Windows.Forms.TextBox()
txt.Top = cLeft * 30
txt.Left = 100
'txt.Text = "TextBox " & Me.cLeft.ToString
cLeft = cLeft + 1
txt.ForeColor = Color.White
txt.BackColor = Color.Gray
txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
txt.Size = New Size(350, 31)
txt.Location = New Point(156, 130 + top1)
txt.TextAlign = HorizontalAlignment.Center
FlowLayoutPanel1.Controls.Add(txt)
End Sub
Private Sub part_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'college part number
Label2.Visible = False
'college path folder
Label3.Visible = False
For m As Integer = 1 To Val(Label2.Text)
AddNewTextBox()
top1 = top1 + 35
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub UpdateUsers()
Using cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Hazim M\Desktop\stud_project\stud_project\Database1.mdf;Integrated Security=True;User Instance=True")
Using cmd As New SqlCommand("INSERT INTO college_part ([name],[coll_of_part],[part_path]) Values (#name,#coll_of_part,#part_path);", cn)
If i < Val(Label2.Text) Then
path1 = Label3.Text & "\" & FlowLayoutPanel1.Controls(i).Text.Trim & Date.Now.Year
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = FlowLayoutPanel1.Controls(i).Text
cmd.Parameters.Add("#coll_of_part", SqlDbType.NVarChar).Value = Label1.Text
cmd.Parameters.Add("#part_path", SqlDbType.NVarChar).Value = path1
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
If Not Directory.Exists(path1) Then
Directory.CreateDirectory(path1)
Else
MsgBox("folder is existing")
End If
End If
End Using
End Using
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
End Class
thank u
I think you need to move dim i Integer=0 to local variable in the Button3_click method. ANd Pass i to the UpdateUser call (add the param to UpdateUser). The current global i keeps adding 1 and eventually out of range.

Assign multidimensional array to DataGridView in VB.NET

I want to assign 2D array to DataGridView.
There are 2 buttons, the first is an array button which will add my inputs to the array every time I press it.
The second button is a submit button that will assign all of the values of the array to the DataGridView.
But I just can't work it out, every time I press the array button, the value is replaced by the new value I inputted.
Here's the code:
Public Class Form2
Dim array(1, 4) As String
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
For i = 0 To array.GetUpperBound(0)
DataGridView1.Rows.Add(array(i, 0), array(i, 1), array(i, 2), array(i, 3))
Next
End Sub
Private Sub btnArray_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnArray.Click
ReDim array(1, 2)
Dim id, name As String
id = txtID.Text
name = txtName.Text
For i = 0 To array.GetUpperBound(0)
array(i, 0) = id
array(i, 1) = name
Next
End Sub
End Class
This code works for me!
Public Class Form2
Dim arrayCopy(10, 1) As String
Dim b As Integer
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
DataGridView1.Rows.Clear()
For i = 0 To b - 1
DataGridView1.Rows.Add(arrayCopy(i, 0), arrayCopy(i, 1))
Next
End Sub
Private Sub btnArray_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnArray.Click
Dim id, name As String
id = txtId.Text
name = txtName.Text
arrayCopy(b, 0) = id
arrayCopy(b, 1) = name
b += 1
End Sub
End Class

Drage and move on click a control on Canvas wpf

I want to Drag Move a userControl which is in a canvas(named as grd) and that canvas is in a larger canvas on which there are a lot of other controls. I am using this code, but it does not work. I am making mouseDown and MouseUpevents of userControl and a MouseMve event of the larger canvas which has a lot of controls.
Where is the problem?
Dim _pressed As Boolean = False
Dim grd As Canvas
Dim mp As Point
Private Sub DeviceIcon_MouseLeftButtonDown(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
_pressed = True
grd = sender
mp = mousePosition
End Sub
Private Sub DeviceIcon_MouseLeftButtonUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
_pressed = False
End Sub
Private Sub gridimgFloor_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles gridimgFloor.MouseMove
If _pressed = False Then Exit Sub
Dim nmp As Point = mousePosition
Dim _x As Integer = nmp.X - mp.X
Dim _y As Integer = nmp.Y - mp.Y
Dim thk As Thickness = grd.Margin
thk.Left = thk.Left + _x
thk.Top = thk.Top + _y
grd.Margin = thk
mp = nmp
End Sub
You should use e.GetPosition(parentControl) to get the position from the event args.

List with remove/delete button

I am developing a WinForms application and I want a ListBox (or a control which provides list of strings) such that when the user hovers the mouse over an item it will show a delete sign for that particular item.
Is there any control available for WinForms to do this?
Setting the ListBox DrawMode to OwnerDrawFixed (or OwnerDrawVariable), you can just handle this yourself with the Mouse events:
Public Class Form1
Private _MouseIndex As Integer = -1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add("String #1")
ListBox1.Items.Add("String #2")
End Sub
Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs) Handles ListBox1.DrawItem
e.DrawBackground()
If e.Index > -1 Then
Dim brush As Brush = SystemBrushes.WindowText
If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
brush = SystemBrushes.HighlightText
End If
e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, brush, e.Bounds.Left + 20, e.Bounds.Top)
If e.Index = _MouseIndex Then
e.Graphics.DrawString("X", e.Font, brush, e.Bounds.Left + 2, e.Bounds.Top)
End If
End If
End Sub
Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListBox1.MouseDown
If _MouseIndex > -1 AndAlso ListBox1.IndexFromPoint(e.Location) = _MouseIndex AndAlso e.Location.X < 20 Then
Dim index As Integer = _MouseIndex
If MessageBox.Show("Do you want to delete this item?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
ListBox1.Items.RemoveAt(index)
ListBox1.Invalidate()
End If
End If
End Sub
Private Sub ListBox1_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox1.MouseLeave
If _MouseIndex <> -1 Then
_MouseIndex = -1
ListBox1.Invalidate()
End If
End Sub
Private Sub ListBox1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListBox1.MouseMove
Dim index As Integer = ListBox1.IndexFromPoint(e.Location)
If index <> _MouseIndex Then
_MouseIndex = index
ListBox1.Invalidate()
End If
End Sub
End Class
Refactor as needed.

WPF asynchronous invoke question

What's wrong in my code? It's not updating the TextBox and the ProgressBar while deleting files.
Imports System.Windows.Threading
Imports System.IO
Class MainWindow
Private Sub bt_Click(ByVal sender As Object,
ByVal e As RoutedEventArgs) Handles bt.Click
Dim sb As New System.Text.StringBuilder
Dim files = IO.Directory.EnumerateFiles(
My.Computer.FileSystem.SpecialDirectories.Temp, "*.*",
SearchOption.TopDirectoryOnly)
Dim count = files.Count
pb.Minimum = 0
pb.Maximum = count
For i = 0 To count - 1
Dim f = files(i)
Dispatcher.BeginInvoke(
New Action(Of String, Integer)(
Sub(str, int)
tb.SetValue(TextBox.TextProperty, str)
pb.SetValue(ProgressBar.ValueProperty, int)
End Sub),
DispatcherPriority.Send,
f, i + 1)
Try
File.Delete(f)
Catch ex As Exception
sb.AppendLine(f)
End Try
Dim exceptions = sb.ToString
Stop
Next
End Sub
End Class
I got this working with the BackgroundWorker object. This places your work in a background thread, with calls to update the UI going through the ProgressChanged event. I also used Invoke instead of BeginInvoke within the work loop, which forces the loop to wait for the UI to become updated before it proceeds.
Imports System.ComponentModel
Imports System.IO
Class MainWindow
Private WithEvents bw As New BackgroundWorker
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As RoutedEventArgs) Handles btn.Click
pb.Minimum = 0
pb.Maximum = 100
bw.WorkerReportsProgress = True
bw.RunWorkerAsync()
End Sub
Private Sub bw_DoWork(ByVal sender As Object,
ByVal e As DoWorkEventArgs) Handles bw.DoWork
Dim sb As New System.Text.StringBuilder
Dim files = IO.Directory.EnumerateFiles(
My.Computer.FileSystem.SpecialDirectories.Temp, "*.*",
SearchOption.TopDirectoryOnly)
Dim count = files.Count
Me.Dispatcher.BeginInvoke(Sub()
tb.Text = "SOMETHING ELSE"
End Sub)
For i = 0 To count - 1
Dim f = files(i)
Dim myI = i + 1
Me.Dispatcher.Invoke(
Sub()
bw.ReportProgress(CInt((myI / count) * 100), f)
End Sub)
'Try
' File.Delete(f)
'Catch ex As Exception
' sb.AppendLine(f)
'End Try
Dim exceptions = sb.ToString
'Stop
Next
End Sub
Private Sub bw_ProgressChanged(
ByVal sender As Object,
ByVal e As ProgressChangedEventArgs) Handles bw.ProgressChanged
Dim fString As String = TryCast(e.UserState, String)
Me.Dispatcher.BeginInvoke(Sub()
tb.Text = fString
End Sub)
End Sub
End Class

Resources