i'm building a slide puzzle in wpf (VB.NET- Visual Studio 2012) and i alredy wrote the code for it but i need to had a stopwatch that will appear at the window loading first time. i also need that the stopwatch will be elapsed and start again when the user shuffles the puzzle. please give me some tips to write the right code. thx.
that's the code for the slide puzzle:
Public Class level2
Dim win(15) As BitmapImage
Dim wrong(15) As BitmapImage
Dim mess(15) As BitmapImage
Dim images(15) As Image
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
Dim h1 As New BitmapImage
h1.BeginInit()
h1.UriSource = New Uri("images2/h1.gif", UriKind.RelativeOrAbsolute)
h1.EndInit()
Dim h2 As New BitmapImage
h2.BeginInit()
h2.UriSource = New Uri("images2/h2.gif", UriKind.RelativeOrAbsolute)
h2.EndInit()
Dim h3 As New BitmapImage
h3.BeginInit()
h3.UriSource = New Uri("images2/h3.gif", UriKind.RelativeOrAbsolute)
h3.EndInit()
Dim h4 As New BitmapImage
h4.BeginInit()
h4.UriSource = New Uri("images2/h4.gif", UriKind.RelativeOrAbsolute)
h4.EndInit()
Dim h5 As New BitmapImage
h5.BeginInit()
h5.UriSource = New Uri("images2/h5.gif", UriKind.RelativeOrAbsolute)
h5.EndInit()
Dim h6 As New BitmapImage
h6.BeginInit()
h6.UriSource = New Uri("images2/h6.gif", UriKind.RelativeOrAbsolute)
h6.EndInit()
Dim h7 As New BitmapImage
h7.BeginInit()
h7.UriSource = New Uri("images2/h7.gif", UriKind.RelativeOrAbsolute)
h7.EndInit()
Dim h8 As New BitmapImage
h8.BeginInit()
h8.UriSource = New Uri("images2/h8.gif", UriKind.RelativeOrAbsolute)
h8.EndInit()
Dim h9 As New BitmapImage
h9.BeginInit()
h9.UriSource = New Uri("images2/h9.gif", UriKind.RelativeOrAbsolute)
h9.EndInit()
Dim h10 As New BitmapImage
h10.BeginInit()
h10.UriSource = New Uri("images2/h10.gif", UriKind.RelativeOrAbsolute)
h10.EndInit()
Dim h11 As New BitmapImage
h11.BeginInit()
h11.UriSource = New Uri("images2/h11.gif", UriKind.RelativeOrAbsolute)
h11.EndInit()
Dim h12 As New BitmapImage
h12.BeginInit()
h12.UriSource = New Uri("images2/h12.gif", UriKind.RelativeOrAbsolute)
h12.EndInit()
Dim h13 As New BitmapImage
h13.BeginInit()
h13.UriSource = New Uri("images2/h13.gif", UriKind.RelativeOrAbsolute)
h13.EndInit()
Dim h14 As New BitmapImage
h14.BeginInit()
h14.UriSource = New Uri("images2/h14.gif", UriKind.RelativeOrAbsolute)
h14.EndInit()
Dim h15 As New BitmapImage
h15.BeginInit()
h15.UriSource = New Uri("images2/h15.gif", UriKind.RelativeOrAbsolute)
h15.EndInit()
win(0) = h1
win(1) = h2
win(2) = h3
win(3) = h4
win(4) = h5
win(5) = h6
win(6) = h7
win(7) = h8
win(8) = h9
win(9) = h10
win(10) = h11
win(11) = h12
win(12) = h13
win(13) = h14
win(14) = h15
win(15) = Nothing
wrong(0) = h4
wrong(1) = h1
wrong(2) = h7
wrong(3) = h14
wrong(4) = h5
wrong(5) = h13
wrong(6) = h8
wrong(7) = h10
wrong(8) = h6
wrong(9) = h2
wrong(10) = h12
wrong(11) = h15
wrong(12) = h3
wrong(13) = h11
wrong(14) = h9
wrong(15) = Nothing
images(0) = flower0
images(1) = flower1
images(2) = flower2
images(3) = flower3
images(4) = flower4
images(5) = flower5
images(6) = flower6
images(7) = flower7
images(8) = flower8
images(9) = flower9
images(10) = flower10
images(11) = flower11
images(12) = flower12
images(13) = flower13
images(14) = flower14
images(15) = flower15
For i As Integer = 0 To wrong.Length - 1
images(i).Source = wrong(i)
Next
End Sub
Sub checkwin()
Dim flag As Boolean = False
For i As Integer = 0 To win.Length - 1
If mess(i) Is win(i) Then
flag = True
Else
flag = False
Exit For
End If
Next
If flag = True Then
lbl2.Content = "You Win!!"
End If
End Sub
Sub checkcells(ByRef pic1 As Image, ByRef pic2 As Image)
If pic2.Source Is Nothing Then
pic2.Source = pic1.Source
pic1.Source = Nothing
End If
End Sub
Sub update()
For i As Integer = 0 To mess.Length - 1
mess(i) = images(i).Source
Next
End Sub
Private Sub flower0_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower0.MouseDown
checkcells(flower0, flower1)
checkcells(flower0, flower4)
update()
checkwin()
End Sub
Private Sub flower1_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower1.MouseDown
checkcells(flower1, flower0)
checkcells(flower1, flower2)
checkcells(flower1, flower5)
update()
checkwin()
End Sub
Private Sub flower2_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower2.MouseDown
checkcells(flower2, flower1)
checkcells(flower2, flower3)
checkcells(flower2, flower6)
update()
checkwin()
End Sub
Private Sub flower3_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower3.MouseDown
checkcells(flower3, flower2)
checkcells(flower3, flower7)
update()
checkwin()
End Sub
Private Sub flower4_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower4.MouseDown
checkcells(flower4, flower0)
checkcells(flower4, flower5)
checkcells(flower4, flower8)
update()
checkwin()
End Sub
Private Sub flower5_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower5.MouseDown
checkcells(flower5, flower1)
checkcells(flower5, flower4)
checkcells(flower5, flower6)
checkcells(flower5, flower9)
update()
checkwin()
End Sub
Private Sub flower6_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower6.MouseDown
checkcells(flower6, flower2)
checkcells(flower6, flower5)
checkcells(flower6, flower7)
checkcells(flower6, flower10)
update()
checkwin()
End Sub
Private Sub flower7_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower7.MouseDown
checkcells(flower7, flower3)
checkcells(flower7, flower6)
checkcells(flower7, flower11)
update()
checkwin()
End Sub
Private Sub flower8_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower8.MouseDown
checkcells(flower8, flower4)
checkcells(flower8, flower9)
checkcells(flower8, flower12)
update()
checkwin()
End Sub
Private Sub flower9_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower9.MouseDown
checkcells(flower9, flower5)
checkcells(flower9, flower8)
checkcells(flower9, flower10)
checkcells(flower9, flower13)
update()
checkwin()
End Sub
Private Sub flower10_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower10.MouseDown
checkcells(flower10, flower6)
checkcells(flower10, flower9)
checkcells(flower10, flower11)
checkcells(flower10, flower14)
update()
checkwin()
End Sub
Private Sub flower11_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower11.MouseDown
checkcells(flower11, flower7)
checkcells(flower11, flower10)
checkcells(flower11, flower15)
update()
checkwin()
End Sub
Private Sub flower12_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower12.MouseDown
checkcells(flower12, flower8)
checkcells(flower12, flower13)
update()
checkwin()
End Sub
Private Sub flower13_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower13.MouseDown
checkcells(flower13, flower9)
checkcells(flower13, flower12)
checkcells(flower13, flower14)
update()
checkwin()
End Sub
Private Sub flower14_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower14.MouseDown
checkcells(flower14, flower10)
checkcells(flower14, flower13)
checkcells(flower14, flower15)
update()
checkwin()
End Sub
Private Sub flower15_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles flower15.MouseDown
checkcells(flower15, flower11)
checkcells(flower15, flower14)
update()
checkwin()
End Sub
Private Sub btnmix_Click(sender As Object, e As RoutedEventArgs) Handles btnmix.Click
Randomize()
Dim num(15) As Integer
Dim rnd1 As Integer
For i As Integer = 0 To 15
rnd1 = Int(Rnd() * (16 - 1) + 1)
Dim flag As Boolean = False
Do While flag = False
For x As Integer = 0 To 15
If rnd1 = num(x) Then
flag = True
End If
Next
If flag = True Then
flag = False
rnd1 = Int(Rnd() * (16 - 1) + 1)
Else
flag = True
End If
Loop
num(i) = rnd1
Dim h16 As New BitmapImage
h16.BeginInit()
h16.UriSource = New Uri("images2/h" & rnd1 & ".gif", UriKind.RelativeOrAbsolute)
h16.EndInit()
images(i).Source = h16
Next
End Sub
'Private Sub hint_Click(sender As Object, e As RoutedEventArgs) Handles hint.Click
' Dim monaLisa As New BitmapImage
' monaLisa.BeginInit()
' monaLisa.UriSource = New Uri("images/monalisa.jpg", UriKind.RelativeOrAbsolute)
' monaLisa.EndInit()
' showMona.Source = monaLisa
'End Sub
End Class
If you make the stopwatch declaration in the class root , then initiate and start it in the window.loaded event and then reset it when the user shuffles the puzzle
Related
Working with Visual Basic (+ DevExpress, WPF) and I've got the fields changing colours based on some validation checks, but the code duplication is bothersome. I feel as though implementing generics is the answer but am struggling with implementation.
Private Sub txt_LostFocus(sender As Object, e As RoutedEventArgs) Handles txtFileNo.LostFocus, txtDataLoc.LostFocus,
txtCltName.LostFocus, dtCurYE.LostFocus, dtPrevYE.LostFocus, seMinThres.LostFocus, cboDivType.LostFocus, cboCltType.LostFocus
Dim todim As String = sender.GetType.ToString
Select Case True
Case todim.EndsWith("TextBox")
makeTB(sender)
Case todim.EndsWith("DateEdit")
makeDE(sender)
Case todim.EndsWith("SpinEdit")
makeSE(sender)
Case todim.EndsWith("ComboBoxEdit")
makeCB(sender)
End Select
End Sub
Private Sub makeTB(sender As Object)
Dim btn As TextBox = CType(sender, TextBox)
If commandFN.bValidNewClient(btn.Name) Then
btn.Background = New SolidColorBrush(Colors.LawnGreen)
Else
btn.Background = New SolidColorBrush(Colors.Red)
End If
End Sub
Private Sub makeDE(sender As Object)
Dim btn As DateEdit = CType(sender, DateEdit)
If commandFN.bValidNewClient(btn.Name) Then
btn.Background = New SolidColorBrush(Colors.LawnGreen)
Else
btn.Background = New SolidColorBrush(Colors.Red)
End If
End Sub
Private Sub makeSE(sender As Object)
Dim btn As SpinEdit = CType(sender, SpinEdit)
If commandFN.bValidNewClient(btn.Name) Then
btn.Background = New SolidColorBrush(Colors.LawnGreen)
Else
btn.Background = New SolidColorBrush(Colors.Red)
End If
End Sub
Private Sub makeCB(sender As Object)
Dim btn As ComboBoxEdit = CType(sender, ComboBoxEdit)
If commandFN.bValidNewClient(btn.Name) Then
btn.Background = New SolidColorBrush(Colors.LawnGreen)
Else
btn.Background = New SolidColorBrush(Colors.Red)
End If
End Sub
Why don't you simply cast the sender argument to Control?:
Private Sub txt_LostFocus(sender As Object, e As RoutedEventArgs) Handles txtFileNo.LostFocus, txtDataLoc.LostFocus,
txtCltName.LostFocus, dtCurYE.LostFocus, dtPrevYE.LostFocus, seMinThres.LostFocus, cboDivType.LostFocus, cboCltType.LostFocus
Dim obj As Control = TryCast(sender, Control)
If obj IsNot Nothing Then
make(obj)
End If
End Sub
Private Sub make(sender As Control)
If commandFN.bValidNewClient(sender.Name) Then
sender.Background = New SolidColorBrush(Colors.LawnGreen)
Else
sender.Background = New SolidColorBrush(Colors.Red)
End If
End Sub
In this instance you can just use the base class, Control, rather than writing a method using generics:
Private Sub txt_LostFocus(sender As Object, e As RoutedEventArgs) Handles txtFileNo.LostFocus, txtDataLoc.LostFocus,
txtCltName.LostFocus, dtCurYE.LostFocus, dtPrevYE.LostFocus, seMinThres.LostFocus, cboDivType.LostFocus, cboCltType.LostFocus
Dim todim As String = sender.GetType.ToString
Dim btn As Control = CType(sender, Control) 'Cast to base class here
If commandFN.bValidNewClient(btn.Name) Then
btn.Background = New SolidColorBrush(Colors.LawnGreen)
Else
btn.Background = New SolidColorBrush(Colors.Red)
End If
End Sub
Using picture boxes overlaid onto an image as seen below.
Click for Form Layout
When the form loads if the student attends the class then the picturebox becomes a green tick. If the student does not attend the class the picturebox becomes blank.
Using SQL I can query the database to return all the classes that a specific student attends.
These classes are stored in an array StudentClass(n)
There are 50 classes on the timetable stored in an array AttendsClass(n). All with a default value of False.
If the student attends a class then the specific attendsclass in the array becomes True.
Once the form is loaded the user can click on a picturebox to select that class and the corresponding attendsclass in the array becomes true.
Finally the user saves the form, inserting the classes back into the database.
The problem I have is in the Sub Form4_Load at the end, I currently have to repeat the same block of code 50 times. That simply checks if the student attends the class then sets the picture box = to an image of a tick on the GUI (_new.jpg).
enter code here
If AttendsClass(1) = True Then
PictureBox1.Image = My.Resources._new
End If
If AttendsClass(2) = True Then
PictureBox2.Image = My.Resources._new
End If
If AttendsClass(3) = True Then
PictureBox3.Image = My.Resources._new
End If
If AttendsClass(4) = True Then
PictureBox4.Image = My.Resources._new
End If
Is it possible to put this into a loop to shorten my code. The code does work but its slow and lengthy so any improvements would be helpful.
Many Thanks Alex Currie
A Level Computing Student
Full Code:
enter code here
Imports System.Data.OleDb
Public Class Form4
Public con As New OleDbConnection
Public ds As New DataSet
Public da As OleDbDataAdapter
Public cb As OleDbCommandBuilder
Public constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" & Application.StartupPath & "\wma.accdb"
Public AttendsClass(50) As Boolean
Public StdID As Integer = Form2.DataGridView1.SelectedRows(0).Cells("StudentID").Value
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Forename As String = Form2.DataGridView1.SelectedRows(0).Cells("Forename").Value
Dim Surname As String = Form2.DataGridView1.SelectedRows(0).Cells("Surname").Value
Student.Text = "Student: " & Forename & " " & Surname
If Not con.State = ConnectionState.Open Then
con.ConnectionString = constring
con.Open()
End If
da = New OleDbDataAdapter("SELECT * FROM StudentClass WHERE StudentId = " & StdID, con)
da.Fill(ds, "Class")
Dim Maxrow As Integer = ds.Tables("Class").Rows.Count
Dim StudentClass(Maxrow) As Integer
For n = 1 To 50
AttendsClass(n) = False
Next
For n = 1 To Maxrow
StudentClass(n) = ds.Tables("Class").Rows(n - 1).Item(1)
For a = 0 To 50
If StudentClass(n) = a Then
AttendsClass(a) = True
End If
Next
Next
If AttendsClass(1) = True Then
PictureBox1.Image = My.Resources._new
End If
If AttendsClass(2) = True Then
PictureBox2.Image = My.Resources._new
End If
If AttendsClass(3) = True Then
PictureBox3.Image = My.Resources._new
End If
If AttendsClass(4) = True Then
PictureBox4.Image = My.Resources._new
End If
End Sub
Private Sub PictureBox1_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox1.Click
If PictureBox1.Image Is Nothing Then
PictureBox1.Image = My.Resources._new
AttendsClass(1) = True
Else
PictureBox1.Image = Nothing
AttendsClass(1) = False
End If
End Sub
Private Sub PictureBox2_Click(sender As System.Object, e As System.EventArgs) Handles PictureBox2.Click
If PictureBox2.Image Is Nothing Then
PictureBox2.Image = My.Resources._new
AttendsClass(2) = True
Else
PictureBox2.Image = Nothing
AttendsClass(2) = False
End If
End Sub
Private Sub PictureBox4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox4.Click
If PictureBox4.Image Is Nothing Then
PictureBox4.Image = My.Resources._new
AttendsClass(4) = True
Else
PictureBox4.Image = Nothing
AttendsClass(4) = False
End If
End Sub
Private Sub PictureBox3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox3.Click
If PictureBox3.Image Is Nothing Then
PictureBox3.Image = My.Resources._new
AttendsClass(3) = True
Else
PictureBox3.Image = Nothing
AttendsClass(3) = False
End If
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If Not con.State = ConnectionState.Open Then
con.ConnectionString = constring
con.Open()
End If
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = con
'Deletes Existing Records To Be rewritten'
cmd.CommandText = "DELETE * FROM StudentClass WHERE StudentID=" & StdID
cmd.ExecuteNonQuery()
For n = 1 To 50
If AttendsClass(n) = True Then
cmd.CommandText = "INSERT INTO StudentClass (StudentID, ClassID) VALUES (" & StdID & "," & n & ")"
cmd.ExecuteNonQuery()
End If
Next
Me.Dispose()
MsgBox("Updated Successfully", MsgBoxStyle.Information, "WMA")
con.Close()
End Sub
End Class
Working example:
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles PictureBox1.Click, ...., PictureBox50.Click
Dim pic As PictureBox = CType(Controls(CType(sender, PictureBox).Name), PictureBox)
'now you have clicked picturebox
'you can change image by pic.Image = ...
'if you want picturebox index, use line below:
Dim picidx As Integer = CInt(CType(sender, PictureBox).Name.Replace("PictureBox", ""))
End Sub
VB2010Ex.
i need to build a 15 picture puzzle and i don't know how to add an image to a button in a way that the image will fill all of the space of the button. or i should do it diffrently?? here is a link of what i need to build:
sahek.co.il/content/full_screen.php?url=http://www.sahek.co.il/…
at the moment all i have is a game with numbers:
Class MainWindow
Private Sub btn1_Click(sender As Object, e As RoutedEventArgs) Handles btn1.Click
'2,4
checkBtn(btn1, btn4)
checkBtn(btn1, btn2)
chechSolved()
End Sub
Private Sub btn2_Click(sender As Object, e As RoutedEventArgs) Handles btn2.Click
'1,3,5
checkBtn(btn2, btn1)
checkBtn(btn2, btn3)
checkBtn(btn2, btn5)
chechSolved()
End Sub
Private Sub btn3_Click(sender As Object, e As RoutedEventArgs) Handles btn3.Click
'2,6
checkBtn(btn3, btn2)
checkBtn(btn3, btn6)
chechSolved()
End Sub
Private Sub btn4_Click(sender As Object, e As RoutedEventArgs) Handles btn4.Click
'1,5,7
checkBtn(btn4, btn1)
checkBtn(btn4, btn5)
checkBtn(btn4, btn7)
chechSolved()
End Sub
Private Sub btn5_Click(sender As Object, e As RoutedEventArgs) Handles btn5.Click
'2,4,6,8
checkBtn(btn5, btn2)
checkBtn(btn5, btn4)
checkBtn(btn5, btn6)
checkBtn(btn5, btn8)
chechSolved()
End Sub
Private Sub btn6_Click(sender As Object, e As RoutedEventArgs) Handles btn6.Click
'3,5,9
checkBtn(btn6, btn3)
checkBtn(btn6, btn5)
checkBtn(btn6, btn9)
chechSolved()
End Sub
Private Sub btn7_Click(sender As Object, e As RoutedEventArgs) Handles btn7.Click
'4,8
checkBtn(btn7, btn4)
checkBtn(btn7, btn8)
chechSolved()
End Sub
Private Sub btn8_Click(sender As Object, e As RoutedEventArgs) Handles btn8.Click
'5,7,9
checkBtn(btn8, btn5)
checkBtn(btn8, btn7)
checkBtn(btn8, btn9)
chechSolved()
End Sub
Private Sub btn9_Click(sender As Object, e As RoutedEventArgs) Handles btn9.Click
'6,8
checkBtn(btn9, btn6)
checkBtn(btn9, btn8)
chechSolved()
End Sub
Sub checkBtn(ByRef butt1 As Button, ByRef butt2 As Button)
If butt2.Content = "" Then
butt2.Content = butt1.Content
butt1.Content = ""
End If
End Sub
Sub chechSolved()
If btn1.Content = "1" And btn2.Content = "2" And btn3.Content = "3" And btn4.Content = "4" And btn5.Content = "5" And btn6.Content = "6" And btn7.Content = "7" And btn8.Content = "8" And btn9.Content = "" Then
MsgBox("הצלחת")
End If
End Sub
Sub shuffle()
Dim a(8) As String
Dim i, j, RN As Integer
Dim flag As Boolean
flag = False
i = 1
a(j) = 1
Do While i <= 8
Randomize()
RN = CInt(Int((8 * Rnd()) + 1))
For j = 1 To i
If (a(j) = RN) Then
flag = True
Exit For
End If
Next
If flag = True Then
flag = False
Else
a(i) = RN
i = i + 1
End If
Loop
btn1.Content = a(1)
btn2.Content = a(2)
btn3.Content = a(3)
btn4.Content = a(4)
btn5.Content = a(5)
btn6.Content = a(6)
btn7.Content = a(7)
btn8.Content = a(8)
btn9.Content = ""
End Sub
Private Sub btnSH_Click(sender As Object, e As RoutedEventArgs) Handles btnSH.Click
shuffle()
End Sub
End Class
Try this in your XAML code:
You can also try Stretch="None", "Fill", "Uniform", or "UniformToFil". Here is more information about Imaging Overview
<Button Height="100" Width="25" >
<Button.Background>
<ImageBrush ImageSource="your image source path" Stretch="Fill" TileMode="None" />
</Button.Background>
</Button>
In XAML you can try,
<Button Name="button1" Width="50" Height="30" Click="OnImageButtonClick">
<Image Source="Images/YourImageName.jpg"></Image></Button>
Or,
from code behind try with,
var brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri("Images/Image1.jpg",UriKind.Relative));
button1.Background = brush;
Or,
BitmapImage btm = new BitmapImage(new Uri("/LoadImages;component/Images/test.png", UriKind.Relative));
Image img = new Image();
img.Source = btm;
img.Stretch = Stretch.Fill;
button2.Content = img;
Remember to set your image build action property as content or resource as you wish.But if you set button background from resource image then use above code like..
Uri resourceUri = new Uri("Images/Image1.jpg", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp;
button1.Background = brush;
And finally another great alternative solution for you..
http://imagebuttonwpf.codeplex.com/
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
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