The goal of this is to provide simple answers of some of the harder visualbasic concepts to grasp (such as drawing to a form or creating grids with a snap-to function) 1)How to draw the the form Code: Protected Overrides Sub OnPaint( _ ByVal e As System.Windows.Forms.PaintEventArgs) 'drawing score Dim g As Graphics = e.Graphics g.DrawString("Score:" & score, _ New Font("Arial", 16), _ Brushes.Black, 1, 1) end sub In This the value of score is drawn to the form at point 1,1; if this score was to continue to increase you would have to invalidate the area where that string is drawn(place a rectangle with visibility set to false over that area and use this code Code: Dim bmpcontainter As RectangleF bmpcontainter = inval.Bounds Me.Invalidate(Rectangle.Round(bmpcontainter)) this code creates a series of points containing the bounds of the rectangle(inval) then uses those points to invalidate only that area 2) how to draw a grid with a snap-to function a) drawing the grid Code: dim g as graphics g=me.creategraphics For x = 0 To 19 For y = 0 To 24 r = New Rectangle(x * 32, y * 32, 32, 32) g.DrawRectangle(Pens.Black, r) Next Next b) the snap-to funtion This code is to made to have any point you pass to it find the nearest point on the grid you made Code: 'declares Dim m_GridX As Integer = 32 Dim m_gridy As Integer = 32 Dim xgrd, ygrd As Integer Code: Private Sub SnapToGrid(ByRef X As Integer, ByRef Y As Integer) Dim ix As Integer = CInt(X / m_GridX) Dim iy As Integer = CInt(Y / m_gridy) xgrd = ix * m_GridX ygrd = iy * m_gridy End Sub To use this: Code: Dim p As Point p = Me.PointToClient(MousePosition) SnapToGrid(p.X, p.Y) this gets the mouse position,finds nearest point on grid stored in xgrd and ygrd 3) drawing lines to the form and keeping them after form refresh, thanks to Calistoga for this add this code Code: Class Line Private m_start As Point, m_end As Point Public Sub New(start As Point, [end] As Point) Me.m_start = start Me.m_end = [end] End Sub Public Property Start() As Point Get Return Me.m_start End Get Set(value As Point) Me.m_start = value End Set End Property Public Property [End]() As Point Get Return Me.m_end End Get Set(value As Point) Me.m_end = value End Set End Property End Class Use this code to make a list of lines to be repainted on form refresh Code: Imports System.Collections.Generic ' Place this in the top of your code file Dim list As List(Of Line) = New List(Of Line) then this code to make a line and add it to list to repaint on form refresh Code: 'change smooothign to hq, drawing line on form with pen point 1 and point 2 Dim pen As New Pen(Brushes.Black, 3) g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality g.DrawLine(pen, mp1, mp2) Dim line As Line = New Line(mp1, mp2) list.Add(line) then use this to redraw all the lines in that list when form is repainted Code: Private Sub Form1_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint For Each L As Line In list Dim pen As New Pen(Brushes.Black, 3) pen.StartCap = Drawing2D.LineCap.RoundAnchor pen.EndCap = Drawing2D.LineCap.ArrowAnchor g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality g.DrawLine(pen, L.Start, L.End) Next End Sub 4) Using the arrow keys Add this function Code: Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Integer) As Integer then in a timer set to every 1ms or so Code: 'pacface is an imagebox If GetAsyncKeyState(Keys.Right) then pacface.Left += 1 end if If GetAsyncKeyState(Keys.Left) then pacface.left-=1 end if If GetAsyncKeyState(Keys.Up) then pacface.Top -= 1 end if If GetAsyncKeyState(Keys.Down) then pacface.Top += 1 end if 5) Creating controls in runtime Code: 'can change picture box to textbox,richtextbox,any control really(few if any exceptions) Dim newsize As New Size(150, 100) Dim pb5 As New PictureBox With pb5 .SizeMode = PictureBoxSizeMode.StretchImage .Name = "Picturebox1" 'resized image is a bitmap i declared earlier (not in this tutorial,out of one of my projects) .Image = resizedimage5 'I incorparated the snap-to grid in this using xgrd and ygrd .Location = New Point(xgrd, ygrd) .Size = newsize .BackColor = Color.Transparent End With 'MUST HAVE ME.CONTROLS.ADD OR IT WONT WORK Me.Controls.Add(pb5) you can add this before me.controls.add() if you want to use the controls events (such as onclick or ontextchanged), you can change the handle added Code: AddHandler pb5.TextChanged, AddressOf Me.pb5_TextChanged Then to use that handle you need a sub that references the name (same name as the words after Addressof, incase you don't know this) This example obviously won't work because in our example our control is a picture box, if you change it to a textbox then this example would be correct Code: Private Sub pb5_TextChanged(ByVal sender As Object, ByVal e As EventArgs) ' stuff here End Sub 6) Removing the controls you just added in runtime THANKS AGAIN TO CALISTOGA 'loops through all control on form and if it is a picturebox or richtext box add it to a list then loop through that list and remove the contols in the list Code: 'declares Dim listc As List(Of Control) = New List(Of Control) Code: Dim c As Control For Each c In Me.Controls If (TypeOf c Is PictureBox Or TypeOf c Is RichTextBox) Then listc.Add(c) End If Next For Each c In listc Me.Controls.Remove(c) Next listc.Clear() me.refresh 7) Check the md5 of application (tests on itself)-from http://forums.mydigitallife.net/threads/32649-VB-NET-or-C-How-to-%28HELP%29 CR32 check is in a thread reply below by The Dev Code: Imports System.Security.Cryptography Public Function MD5Sec(ByVal filepath As String) As String Using reader As New System.IO.FileStream(filepath, IO.FileMode.Open, IO.FileAccess.Read) Using md5 As New System.Security.Cryptography.MD5CryptoServiceProvider Dim hash() As Byte = md5.ComputeHash(reader) Return ByteArrayToString(hash) End Using End Using End Function Private Function ByteArrayToString(ByVal arrInput() As Byte) As String Dim sb As New System.Text.StringBuilder(arrInput.Length * 2) For i As Integer = 0 To arrInput.Length - 1 sb.Append(arrInput(i).ToString("X2")) Next Return sb.ToString().ToUpper End Function 'usage below, mine is in the form load event and 'Self_MD5' can be a textbox, label, linklabel etc Try Self_MD5.Text = MD5Sec(Environment.CurrentDirectory + "\applicationnamehere.exe") Catch md5null As Exception Self_MD5.Text = "" End Try 8) changing reg keys and checking if they exist-BE VERY SURE U MODIFY THE REG KEY LOCATION BECAUSE MY EXAMPLES WILL CHANGE THE VALUES FOR HDD MODE (are and excerpt from my AHCI changer app) to check if a key exists Code: Imports System.IO -need to import io for all file operations including reg keys Code: 'if get value returns nothing then exists3 (e3) = false else returns true If My.Computer.Registry.GetValue _ ("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\msahci", "Start", Nothing) Is Nothing Then e3 = False Else e3 = True End If how to change a key Code: If e3 = True Then Dim autoshell = My.Computer.Registry.LocalMachine.OpenSubKey("System\CurrentControlSet\Services\msahci", True) '' Set the value to 0 autoshell.SetValue("Start", 0) autoshell.Close() End If how to check the value of a key i use byte because it's either 1 or 0 so no point in integer and using more memory Code: Dim v3 as byte Code: If e3 = True Then v3 = My.Computer.Registry.GetValue _ ("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\msahci", "Start", Nothing) End If Code: if v3=0 then 'do whatever 9) close all open windows -Josh Cell, http://forums.mydigitallife.net/threads/33487-VB-NET-All-Active-window-will-be-and-close-it Code: For Each MainProc As Process In Process.GetProcesses(Environment.MachineName) If (MainProc.MainWindowHandle <> IntPtr.Zero) Then MainProc.Kill() End If Next 10) create a restore point without a dialog (silently) -link to thread adapted from this vb6 code Code: 'will create a restore point silently, may freeze app for ~5 seconds, this can be fixed with a background worker or a new thread Dim obj As Object obj = GetObject("winmgmts:{impersonationLevel=impersonate}!root/default:SystemRestore") 'The date and ID are auto added Call obj.CreateRestorePoint("Give it a name", 12, 100) 11) check how many restore points are on a computer (if you just made on using step 10, you must restart the app for it to count your new restore) Code: Public Sub ListPoints() 'Adds all Restore Points to a ListView Dim o As Object Dim sr As Object Dim num As Byte 'Get all points and add them to "o" o = GetObject("winmgmts:root/default").InstancesOf("SystemRestore") 'Scroll through "o" For Each sr In o num += 1 'Adds a point to a ListView then shows num of restore not that after 'creating the restore it will not show a nother restore until restarting app ListView2.Items.Add(sr) MessageBox.Show(num) Next sr End Sub 12) Remap function- this will convert a large range into a smaller range, say you have x in the range 500-0(the range is the numbers that say could be x on input from a joystick), you can remap x to a smaller range to say 50-0. If you need an example of how to implement this my signature has a joystick program that uses the map function feel free to download it and look at the source Code: Public Function map(x As Integer, inmin As Integer, inmax As Integer, outmin As Integer, outmax As Integer) 'x is the value in a range, the first range is the range that x is in, second is range x is being converted to Dim int As Integer int = (x - inmin) * (outmax - outmin) / (inmax - inmin) + outmin Return Math.Round(int) End Function STATUS OF UPDATES: added #12
Application CRC32 hashing(checks on self) Imports: Code: #Region "Imports" Imports System.Security Imports System.Security.Cryptography #End Region Code: #Region "CRC32 Hashing" Private filePath As String Private fileStream As FileStream Private streamWriter As StreamWriter Public Delegate Function ReturnTextDelegate() As String Public Function GetCrc32(ByRef stream As IO.Stream) As Integer Dim crc32Table() As Integer Const BufferSize As Integer = 1024 Dim dwPolynomial As Integer = &HEDB88320 Dim i As Integer, j As Integer ReDim crc32Table(256) Dim dwCrc As Integer For i = 0 To 255 dwCrc = i For j = 8 To 1 Step -1 If (dwCrc And 1) Then dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF dwCrc = dwCrc Xor dwPolynomial Else dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF End If Next j crc32Table(i) = dwCrc Next i Dim crc32Result As Integer crc32Result = &HFFFFFFFF Dim buffer(BufferSize) As Byte Dim readSize As Integer = BufferSize Dim count As Integer = stream.Read(buffer, 0, readSize) Dim c As Integer Dim iLookup As Integer Dim tot As Integer = 0 Do While (count > 0) For c = 0 To count - 1 iLookup = (crc32Result And &HFF) Xor buffer(c) crc32Result = ((crc32Result And &HFFFFFF00) \ &H100) And &HFFFFFF crc32Result = crc32Result Xor crc32Table(iLookup) Next c count = stream.Read(buffer, 0, readSize) Loop GetCrc32 = Not (crc32Result) End Function #End Region Usage: Code: Try Dim mainapp As String = CStr(AppDomain.CurrentDomain.FriendlyName) Dim crc As Integer = 0 Dim path As String = DirectCast(Invoke(New ReturnTextDelegate(AddressOf mainapp.ToString), New Object(-1) {}), String) Dim stream As FileStream = File.OpenRead(path) crc = GetCrc32(stream) app_checksum.Text = String.Format("{0:X8}", crc) stream.Close() Catch ex As Exception MsgBox(ex.message) End Try
I want to learn visual basic, but I don't have its program. There are many version in many thread, and there isn't stick thread or official thread. So where I can get that program link? And maybe with its key too Sorry for my poor english, thanks a lot
When you say "its program" I assume you mean the IDE or the program used to write visualbasic code inside. For that i highly recommend the Microsoft Visual Studio express 2012- link http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-products P.S your english is fine if i can read it and understand the point then you're good, and if you need any further help fell free to make your own thread right here in mixed languages and i'll answer your questions
Hi, well if you wanna learn a programming language (C/C++/C#/Vb or any other language), you must have an IDE to dev' with, check Code::Blocks for free and open source, or VS 2012 the M$ one. Also this can be useful for some tips: http://www.codeproject.com/