Snippets Part 3
I will Be adding more as I write them
Empty Recycling Bin
Declarations And Variables
Code:
Private Declare Function SHEmptyRecycleBin Lib "shell32.dll" Alias "SHEmptyRecycleBinA" (ByVal hWnd As Int32, ByVal pszRootPath As String, ByVal dwFlags As Int32) As Int32
Private Declare Function SHUpdateRecycleBinIcon Lib "shell32.dll" () As Int32
Private Const SHERB_NOCONFIRMATION = &H1
Private Const SHERB_NOPROGRESSUI = &H2
Private Const SHERB_NOSOUND = &H4
Empty Recycling Bin Sub
Code:
Private Sub takeoutthetrash()
SHEmptyRecycleBin(Me.Handle.ToInt32, vbNullString, SHERB_NOCONFIRMATION + SHERB_NOSOUND)
SHUpdateRecycleBinIcon()
End Sub
Code to call the empty recycling bin sub
Add a Windows User
Add 3 TextBox's
Add 1 Button
TextBox1 will be for the new Username
Textbox2 will be the password field
Textbox3 will be the verify password field
Button_Click Event for button
Code:
Dim username As String = TextBox1.Text
Dim password As String = TextBox2.Text
'Match the passwords, if they match, then add user
If TextBox2.Text = TextBox3.Text Then
Shell("net user " & username & " " & password & " /add")
MessageBox.Show("Windows User Created)
Else
MessageBox.Show("Passwords are different")
End If
Get Hardware Serial
Create a New Class and add this code
Code:
Public Class HardDrive
Private dsk_model As String
Private dsk_type As String
Private dsk_serialNo As String
Public Property Model() As String
Get
Return dsk_model
End Get
Set(ByVal value As String)
dsk_model = value
End Set
End Property
Public Property Type() As String
Get
Return dsk_type
End Get
Set(ByVal value As String)
dsk_type = value
End Set
End Property
Public Property serialNo() As String
Get
Return dsk_serialNo
End Get
Set(ByVal value As String)
dsk_serialNo = value
End Set
End Property
End Class
Now Add a textbox to your form, set it to multiline=true
View Code
In the namespace
Code:
Imports System
Imports System.Collections
Imports System.Management
Variables and Declarations
'Dim appname as system.STATthreadattribute()
Dim WindowsApplication1 As System.STAThreadAttribute()
In Form1 Load add
Code:
Dim SerialHD As New ArrayList()
Dim Obsearch As New ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive")
Dim HDinfo As New ManagementObject()
For Each HDinfo In Obsearch.Get
Dim hd As New Class1.HardDrive()
hd.Model = HDinfo("Model").ToString()
hd.Type = HDinfo("InterfaceType").ToString()
SerialHD.Add(hd)
Next
Dim searcher1 As New ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia")
Dim i As Integer = 0
For Each HDinfo In searcher1.Get()
Dim hd As Class1.HardDrive
hd = SerialHD(i)
If HDinfo("SerialNumber") = "" Then
hd.serialNo = "None"
Else
hd.serialNo = HDinfo("SerialNumber").ToString()
i += 1
End If
Next
Dim hd1 As Class1.HardDrive
Dim ii As Integer = 0
For Each hd1 In SerialHD
ii += 1
TextBox1.Text = TextBox1.Text + "Serial No: " + hd1.serialNo + Chr(13) + Chr(10) + Chr(13) + Chr(10)
Next
Clear All Controls in a Form (MSDN Standard CODE)
Code:
For Each objControls As Control In Me.Controls
If TypeOf objControls Is TextBox Then
CType(objControls, TextBox).Text = String.Empty
End If
If TypeOf objControls Is DropDownList Then
If Not CType(objControls, DropDownList).ID.Contains("ddlUSTYear") Then
CType(objControls, DropDownList).SelectedIndex = 0
End If
End If
If TypeOf objControls Is CheckBox Then
CType(objControls, CheckBox).Checked = False
End If
If TypeOf objControls Is RadioButton Then
CType(objControls, RadioButton).Checked = False
End If
Next
Read File Content
Code:
Public Shared Function ReadFileContent(ByVal sFile As String) As String
Dim GetFileC As String = String.Empty
If File.Exists(sFile) Then
Dim ActualC As StreamReader = File.OpenText(sFile)
Try
ActualC = File.OpenText(sFile)
GetFileC = ActualC.ReadToEnd()
Catch exp As Exception
Throw ex
Finally
If Not Nothing Is ActualC Then
ActualC.Close()
End If
End Try
End If
Return GetFileC
End Function
To Call it Use
ReadFileContent ("File Location")
Get File Extension
Code:
Public Shared Function GetExtension(ByVal strFileName As String) As String
If (strFileName.Length > 0) Then
stringDoc = strFileName.Split(characterA)
Return "." + stringDoc(stringDoc.Length - 1)
Else
Return ""
End If
End Function
To use Call the Function
GetExtension ("File Location and Name")
Prevent Pasting in a Textbox with Ctrl + V
Code:
' This is Used in the Keypressed method, You can use the same concept on click , or Mouse Click, etc....
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
System.Windows.Forms.Clipboard.Clear()
End Sub
Random Password String From GUID
Code:
Public Function GetRandomPasswordUsingGUID1(ByVal length As Double) As String
Dim GR As String = System.Guid.NewGuid.ToString
GR = GR.Replace("-", String.Empty)
If length <= 0 OrElse length > GR.Length Then
Throw New ArgumentException("Length should be between 1 and " & GR.Length)
End If
Return GR.Substring(0, length)
End Function
Use, (Sim liar to SOAP WSDL API, or Web Services in ASP.net)
GetRandomPasswordUsingGUID1(Legth Of Password)
Example
Button_Click Event
MsgBox(GetRandomPasswordUsingGUID1(25)
Encrypt Text
Code:
Public Function EnDeCrypt(ByVal Text As String) As String
Dim TCr As String = "", i As Integer
For i = 1 To Len(Text)
If Asc(Mid$(Text, i, 1)) < 128 Then
TCr = CType(Asc(Mid$(Text, i, 1)) + 128, String)
ElseIf Asc(Mid$(Text, i, 1)) > 128 Then
TCr = CType(Asc(Mid$(Text, i, 1)) - 128, String)
End If
Mid$(Text, i, 1) = Chr(CType(TCr, Integer))
Next i
Return Text
To use
MsgBox (EnDecrypt("Word to encrypt")
Example:
Msgbox (Endecrypt("Food")
Will encrypt the word food, you can use this in whole textbox's etc.
Get List Of Installed Printers on your machine
Add a Combo-Box to your form
In Namespace
[code]
Imports System.Drawing
Form Load Event
<<<@!14!@>>>
Force Application To Require Admin Approval
Show All files in your Solutions Explorer
Navigate to the Bin Folder ----> Debug ----> Applicationname.Vshost.exe.Manifest File
Double Click it and
add this code
<<<@!15!@>>>
Replacing it with the existing code
or
Use the existing code
Code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
The information is as follows
requireAdministrator:
highestAvailable:
asInvoker: Vb.net Default
So for this particular case it would be
Code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator:" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
Change Background Color of Form with Color Dialog
Add a Color Dialog Box to your Form
Add a button
on button click Event
Code:
Dim Bcolor As New ColorDialog()
Bcolor.ShowDialog()
Me.BackColor = Bcolor.Color
Print a Textbox
* Every where I go , I see all this complex code, and all these Imports and just ugly code, I think a rumor started along time ago that printing a single textbox was hard and required system.drawing and ever since then, everyone just copied and pasted everyone else's code and slightly modified it and called it as thier own. I am here to break that rumor
Simple Print TextBox 1
Code:
PrintDocument1.PrinterSettings.Copies = 1
PrintDocument1.Print()
Then Add this
Code:
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
e.Graphics.DrawString(TextBox1.Text, TextBox1.Font, Brushes.Blue, 100, 100)
End Sub
Here is how to Create your own sleep method which will pause what you want to pause, but still allow the application to function
Code:
Private Sub Sleep(ByVal PauseTime As Double)
Dim Tind As Int16
For Tind = 1 To PauseTime / 50
Threading.Thread.Sleep(50)
Application.DoEvents()
Next
End Sub
Note: the Application.DoEvents Will allow your application to function normally during sleep
Now you can call a "proper" Sleep
Code:
Sleep(time to sleep)
Changing XML Node Values
Code:
Dim root As XElement = XElement.Load("Location\Filename.xml")
Dim xt As XElement = (From el In root.Descendants("Node1") _
Select el).First()
xt.SetValue("New Value")
root.Save("Location\Filename.xml")
You can do this dynamically as well by using the value fields with combo-box data or textbox values, etc.
Create A Tab Delimited Text File with listcheckedbox
I notated everything to help you get the basic understanding, Hope this works without special encoding. (as far as the .gct is concerned)
Using ChecklistBox
---- Add Two Buttons
---- Add One TextBox
--- Add One CheckedListBox
Button 1 Text should be - Add
Button 2 Text should be - Save as .GCT
Button One Click Event
' This adds the item of textbox1.text to your checkedlistbox
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CheckedListBox1.Items.Add(TextBox1.Text)
End Sub
Button Two Click Event
' This Calls the sub SaveCheckedlistBox which will save the checked list box of your choice
' The format is SaveCBox(clb)
' CLB = the name of the checkedlistbox you want to save as tab delimited
Code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SaveCBox(CheckedListBox1)
End Sub
Now add this code below the above
' This is the part of the sub that saves the checked listbox as a .GCT Text file, with tabbed delimited format
Code:
Private Sub SaveCBox(ByVal clb As CheckedListBox)
' Declares Save dialog as a new instance of Save File Dialog
Dim SaveDialog As New SaveFileDialog
' Allows us to add extensions, if this is false then extensions would be *.* All Files
SaveDialog.AddExtension = True
' The default extension is set to .GCT (the format you are looking for)
SaveDialog.DefaultExt = ".gct"
' This sets the save as combo-box items
' The Format is "Description|Extension"
SaveDialog.Filter = "GCT Files|*.GCT|All Files|*.*"
SaveDialog.FilterIndex = 0
' Sets the Text on the Title
SaveDialog.Title = "Save List Box as GCT"
' Saves the listcheckedbox as a .gct in tab delimited format.
If SaveDialog.ShowDialog = DialogResult.OK Then
Dim sw As New System****.StreamWriter(SaveDialog.FileName)
For i As Integer = 0 To clb.Items.Count - 1
Dim t As Boolean = clb.GetItemChecked(i)
sw.WriteLine(clb.Items(i).ToString & ControlChars.Tab & t.ToString)
Next
sw.Close()
End If
SaveDialog.Dispose()
End Sub
Run Application from Resources
Name Space
Now this in a button click (or whet ever triggers the event)
Code:
Dim RPath As String = Application.StartupPath & "\File.exe" 'File.exe will be a temp name given to your exe, you can make it anything you want, or keep it as is.
' Will create the file with the given name
Using CreateFile As New FileStream(RPath, FileMode.Create)
CreateFile.Write(My.Resources.YourResource, 0, My.Resources.YourResource.Length)
End Using
' Start the application
Process.Start(RPath)
Note: "Your Resource" in my code example above needs to be the EXE name without the exe extension, so for example, if you add notepad.exe as a resource, then the code would be
Code:
Dim RPath As String = Application.StartupPath & "\File.exe"
Using CreateFile As New FileStream(RPath, FileMode.Create)
CreateFile.Write(My.Resources.Notepad, 0, My.Resources.Notepad.Length)
End Using
Process.Start(RPath)
Opening and saving .txt files
Visual Basic Programming - MPGH - MultiPlayer Game Hacking
Using SAPI/Making your computer "Speak":
Visual Basic Programming - MPGH - MultiPlayer Game Hacking
Visual Basic .Net RunDll32 Commands
Display the BlueScreen Of Death
Code:
Shell ("rundll32 user,disableoemlayer")
'Open Control Panel
Code:
Shell("rundll32.exe shell32.dll Control_RunDLL")
'Add Or Remove Programs
Code:
Shell("rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,1")
'Turn Off Computer
Code:
Shell ("Rundll32.exe user32.dll,LockWorkStation")
'Load Mouse Properties
Code:
Shell ("Rundll32.exe shell32.dll,Control_RunDLL main.cpl @0")
'Keyboard Properties
Code:
Shell("Rundll32.exe shell32.dll,Control_RunDLL main.cpl @1")
'Printer Properties
Code:
Shell( "Rundll32.exe shell32.dll,Control_RunDLL main.cpl @2")
'Fonts Folder
Code:
Shell ("Rundll32.exe shell32.dll,Control_RunDLL main.cpl @3")
'Internet Properties
Code:
Shell ("rundll32.exe shell32.dll,Control_RunDLL inetcpl.cpl,,5")
'Keyboard Accessibility
Code:
Shell ("rundll32.exe shell32.dll,Control_RunDLL access.cpl,,1")
'Sound / Accessibility
Code:
Shell("rundll32.exe shell32.dll,Control_RunDLL access.cpl,,2")
Display Accessibility
Code:
Shell ("rundll32.exe shell32.dll,Control_RunDLL access.cpl,,3")
'Display Settings
Code:
Shell ("rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,0")
Screen Saver
Code:
Shell("rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,1")
Internet Security
Code:
Shell ("rundll32.exe shell32.dll,Control_RunDLL inetcpl.cpl,,1")
Display Properties Window
Code:
Shell("rundll32.exe shell32.dll,Control_RunDLL desk.cpl")
Networking
Code:
Shell ("rundll32.exe shell32.dll,Control_RunDLL netcpl.cpl")
System Properties
Code:
Shell ("rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl")
Lock the Keyboard
Code:
Shell ("rundll32.exe keyboard,disable")
Disable the Mouse
Code:
Shell ("rundll32.exe mouse,disable")
Swap Mouse Buttons (left = right and vice Versa )
Code:
Shell ("rundll32.exe user.dll,swapmousebutton")
Shut Down Computer
Code:
Shell ("rundll32.exe shell32.exe,SHExitWindowsEx 1")
Log Off
Code:
Shell ("rundll32.exe shell32.exe,SHExitWindowsEx 0")
Activate a Running Process By Name
Code:
AppActivate("Untitled - Notepad")
Activate Running Process by id
Code:
Dim processID As Integer
processID = Shell("NOTEPAD.EXE", AppWinStyle.NormalFocus)
AppActivate(processID)
SendKeys To application
Code:
SendKeys.SendWait("{ENTER}")
Write to application log file.
Code:
My.Application.Log.WriteEntry("Entry Here")
Define a Structure
Code:
Structure MyStructure
Public ValueOne As Integer
Public ValueTwo As Boolean
End Structure
Sound
Loop a Sound
Code:
My.Computer.Audio.Play("SoundFile.wav", AudioPlayMode.BackgroundLoop)
Play Sound
Code:
My.Computer.Audio.Play("ringout.wav", AudioPlayMode.WaitToComplete)
Stop Playing Sound
Code:
My.Computer.Audio.Stop()
Code:
' Use a Graphics object to measure the button's text. Then add blanks to leave space on either side.
Dim surface As Graphics = Button1.CreateGraphics
Dim textSize As SizeF = surface.MeasureString(" " & Button1.Text & " ", Button1.Font)
surface.Dispose()
Button1.Width = CInt(textSize.Width)
Create a Pen
Code:
Dim myPen As System.Drawing.Pen
myPen = New System.Drawing.Pen(Color.Black)
Display a animated Gif
Code:
PictureBox1.Image() = Image.FromFile("gifname.gif")
_______________
Convert Mouse Coordinates to screen coordinates
Code:
Private Sub Me_MouseDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Me.MouseDown
Dim screenPoint As Point
screenPoint = Me.PointToScreen(New Point(e.X, e.Y))
End Sub
Create a Transparent form
Code:
frmTransparentForm.Opacity = 0.90
Determine modifier key pressed
Code:
Private Sub Me_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If (Control.ModifierKeys And Keys.Shift) = Keys.Shift Then
End If
End Sub
Remove Title Bar
Code:
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
Create Email Message
Code:
Dim message As New MailMessage("sender@address", "from@address", "Subject", "Message Text")
Dim emailClient As New SmtpClient("Email Server Name")
emailClient.Send(message)
Use Serial Port To Dial A Number
Code:
Using comPort As SerialPort = My.Computer.Ports.OpenSerialPort("COM1", 2400)
comPort.DtrEnable = True
comPort.Write("555-555-5455" & vbCrLf)
End Using
____________
Search Files for an expression
Code:
Dim files As ReadOnlyCollection(Of String)
files = My.Computer.FileSystem.FindInFiles("C:\", "what you are looking for goes in here IE Food", True, FileIO.SearchOption.SearchAllSubDirectories, "*.txt")
_________________________________
A more advanced basic spammer
Add 2 Text boxes and one button
Name Space
- I notated everything
Code:
'Used to import COM and Invoke services , needed for DLL Import
Imports System****ntime.InteropServices
Functions (just below public call formname
Code:
' This function will allow us to get a window and find it, by window name
' You can use this anytime you need to find a window by window name for any reason
<DllImport("USER32.DLL", CharSet:=CharSet.Unicode)> _
Public Shared Function WindowName(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
and below that
Code:
' This function will allow us set the foreground window
' This will bring the window we need to send the keystrokes to upfront
<DllImport("USER32.DLL")> _
Public Shared Function UpFront(ByVal hWnd As IntPtr) As Boolean
End Function
On the button click event
Code:
' when you use try, it litterly means "attempt the following code before catch, if the "code is unseccesful"
' then catch the exception and display it in a message box , you can use list boxes for storing errors in a database
' but that is a little more advaced
Try
' (apph = name I have chosen for the declaration, you can choose any thing you wish)
' Declaring AppH as IntPtr which is used represent a pointer or a handle, in this case we are setting = to windowname
' which is a function I created above to set the window to sendkeys to, the format is
' (ByVal lpClassName As String, ByVal lpWindowName As String)
' I Use Nothing as the IPclassname, if you know the IPclassname you can use it.
' In textbox1 you can add the name of the window to check for
'lets use notepad, the name of a unnamed notepad is Unitled - Notepad
' so if you were to open notepad without a given name, and put Unitled - Notepad in textbox1
'this would continue and function, if not you will get an error
Dim AppH As IntPtr = WindowName(Nothing, TextBox1.Text)
'IntPtr is a set value so if the value is 0 [window name is wrong or not a open application, error])
If AppH = IntPtr.Zero Then
MsgBox("Chosen Application is not Running")
Return
End If
' If successful bring the window to the foreground
UpFront(AppH)
'sendkeys the content of textbox2
SendKeys.SendWait(TextBox2.Text)
Catch ex As Exception
MsgBox(ex.Message)
End Try