Thread: Snippets Vault

Page 1 of 8 123 ... LastLast
Results 1 to 15 of 113

Hybrid View

  1. #1
    NextGen1's Avatar
    Join Date
    Dec 2009
    Gender
    male
    Location
    Not sure really.
    Posts
    6,312
    Reputation
    382
    Thanks
    3,019
    My Mood
    Amazed

    Snippets Vault

    https://www.mpgh.net/forum/160-tools/...l-release.html

    The Snippet Vault:
    The Snippet Vault is a Stickied thread created in a effort to answer
    those small questions before they have to be asked.


    The rules of this thread is simple:

    • This thread is open and will stay open.
    • This thread is stickied and therefore can be posted in > 7 days.
    • You can post in this thread, but if you post anything it [b] contain]/b] a snippet of code as well.
      for the sake of keeping it uniform
    • This section is not for "How to Run Visual Basic .NET" or "Download Visual Basic .NET Express from" , It will be used for Snippets of code only.
    • If you leech the snippet, Give credit, (even if it is MSDN Standard)
    • Check the posts before yours, don't post existing snippets or alternatives to snippets, it is not needed and will be removed.


    Post your Snippets here and share them.

    For our purposed when I say Code snippets that includes Very short tutorial (like add 2 text boxes and goto code)(Nothing extensive, save those tutorials for the tutorial section.) or a few lines of code to accomplish something Small.

    My Snippets (gathered from my tutorials)

    - Note: Some code snippets are MSDN standard.

    Just another collection of code snippets from me to you.
    (also check out my UI Snippets)

    Use this as a "Quick Reference Guide" when you need to remember "how to it"

    VB.net Code Snippets Reference

    Move a File

    [highlight=vbnet]
    My.Computer.FileSystem.CopyFile("FileLocaion", "FileDestination")
    [/highlight]

    Save Window Size Settings

    [highlight=vbnet]
    If Me.WindowState = FormWindowState.Normal Then
    My.Settings.WindowSize = Me.Size
    End If
    [/highlight]

    Save Windows Location

    [highlight=vbnet]
    If Me.WindowState = FormWindowState.Normal Then
    My.Settings.WindowLocation = Me.Location
    End If
    [/highlight]

    Loads a windows previous size from settings

    [highlight=vbnet]
    If Not My.Settings.WindowSize.Width = 0 Then
    Me.Size = My.Settings.WindowSize
    End If
    [/highlight]

    Loads Previous Locations From Settings

    [highlight=vbnet]
    If Not My.Settings.WindowLocation.X = 0 Then
    Me.Location = My.Settings.WindowLocation
    End If
    [/highlight]

    Auto Update Previous Version Settings

    [highlight=vbnet]
    If My.Settings.CallUpgrade = True Then
    My.Settings.Upgrade()
    My.Settings.CallUpgrade = False
    End If
    [/highlight]


    Minimize to tray

    Form Load (Set Icon)
    [highlight=vbnet]
    Me.NotifyIcon1.Icon = Me.Icon
    [/highlight]


    Form Load, Set it true

    [highlight=vbnet]
    Me.NotifyIcon1.Visible = true
    [/highlight]


    VB Syntax for Minimizing to System Tray

    [highlight=vbnet]
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    NotifyIcon1.Visible = False
    End Sub

    Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
    Try
    Me.Show()
    Me.WindowState = FormWindowState.Normal
    NotifyIcon1.Visible = False

    Catch ex As Exception
    MsgBox(ex.Message)
    End Try
    End Sub

    Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
    Try
    If Me.WindowState = FormWindowState.Minimized Then
    Me.WindowState = FormWindowState.Minimized
    NotifyIcon1.Visible = True
    Me.Hide()
    End If

    Catch ex As Exception
    MsgBox(ex.Message)
    End Try
    End Sub
    [/highlight]


    Show Balloon Tip
    (use on minimize, but can be adjusted for anything

    [highlight=vbnet]
    notifyIcon1.ShowBalloonTip(3000, "Your App", ("Application has not closed" & DirectCast((13), [Char]) & "You can access it from System tray") + DirectCast((13), [Char]) & "Right click the Icon to exit.", ToolTipIcon . info
    [/highlight]

    Save Checkbox Settings

    Form Load

    [highlight=vbnet]
    CheckBox1.Checked = GetSetting(Application.ProductName, Application.ProductName, "CheckBox1")
    [/highlight]

    Form Closing

    [highlight=vbnet]
    SaveSetting(Application.ProductName, Application.ProductName, "CheckBox1", CheckBox1.Checked)
    [/highlight]

    This can be changed/modified for other components as well

    Get and Save Settings

    Get Setting:

    [highlight=vbnet]
    MySettingValue = My.Settings.Default.SettingName
    [/highlight]

    [highlight=vbnet]
    My.Settings.Default.SettingName = ConnString
    My.Settings.Save()
    [/highlight]

    Send Input to Send Mouse Clicks

    Declare
    [highlight=vbnet]
    Public Structure MOUSEINPUT
    Public dx As Integer
    Public dy As Integer
    Public mouseData As Integer
    Public dwFlags As Integer
    Public dwtime As Integer
    [/highlight]

    Code:

    [highlight=vbnet]
    Public Sub MouseClick()

    Dim inputme(0) As INPUT_TYPE

    inputme(0).xi.dx = 0
    inputme(0).xi.dy = 0
    inputme(0).xi.mouseData = 0
    inputme(0).xi.dwFlags = M_MOVE + M_LD + M_LU
    inputme(0).xi.dwtime = 0
    inputme(0).xi.dwExtraInfo = 0
    inputme(0).dwType = INPUT_MOUSE

    SendInput(1, inputme(0), Len(inputme(0)))
    SetCursorPos(xyC)

    End Sub

    [/highlight]

    Get Windows Title

    Declaration:This works with one textbox and one Button, But the code can be used where ever you like.

    [highlight=vbnet]
    Dim mce As Boolean

    Private Declare Function SetCapture Lib "user32" (ByVal hwnd As Long) As Long
    Private Declare Function ReleaseCapture Lib "user32" () As Long
    Private Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As Long
    Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
    Private Declare Function ClientToScreen Lib "user32" (ByVal hwnd As Long, lpPoint As POINTAPI) As Long
    [/highlight]

    Module

    [highlight=vbnet]
    Type POINTAPI
    x As Long
    y As Long
    End Type
    [/highlight]

    Code

    [highlight=vbnet]
    Private Sub Button1_Click()
    mse = True
    intRetVal = SetCapture(hwnd)
    End Sub

    Private Sub Form_Load()

    mse = False

    End Sub

    Private Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
    Dim window As Long
    Dim buffer As String * 1024
    Dim ptPoint As POINTAPI

    If mse Then

    ptPoint.x = x
    ptPoint.y = y
    retval = ClientToScreen(hwnd, ptPoint)

    window = WindowFromPoint(ptPoint.x, ptPoint.y)
    lngRetVal = GetWindowText(window, buffer, 1024)
    Text1.Text = buffer
    End If
    End Sub
    [/highlight]

    Play Wav File

    Declarations

    [highlight=vbnet]
    Public Const SND_ALIAS = &H10000
    Public Const SND_ASYNC = &H1
    Public Const SND_LOOP = &H8
    Public Const SND_NOWAIT = &H2000
    Public Const SND_SYNC = &H0
    [/highlight]

    Code
    (place in any event or trigger you like)

    [highlight=vbnet]
    Dim sps As Long
    sps = sndPlaySound("location/file.wav", SND_SYNC)
    [/highlight]


    Detect of computer has a wav compatible Sound Card...

    Declarations

    [highlight=vbnet]
    Private Declare Function waveOutGetNumDevs Lib "winmm" () As Long
    [/highlight]

    Code

    [highlight=vbnet]

    Dim w As Long

    w = waveOutGetNumDevs()

    If i > 0 Then (there would have to be atleast 1 sound card)
    MsgBox "Wav Compatible"
    Else
    MsgBox "Non Wav Comp."
    End If
    [/highlight]

    A Collection Of UI Code Snippets to enhance your users interface.

    Check Mouse Click

    [highlight=vbnet]
    Dim clickd As String
    clickd = e.Button()
    Select Case clickd
    Case 2097152 '(right mouse Value)
    MsgBox("You Right Clicked")
    Case 1048576 '(left Mouse Value)
    MsgBox("You Left Clicked")
    End Select
    MsgBox(clicktext)
    [/highlight]

    Disable (X) On form
    (I have a full tutorial in my sig, but here is the code snippet, I wanted to include it in this list because it comes in handy)

    [highlight=vbnet]
    Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As IntPtr, ByVal nPosition As Integer, ByVal wFlags As Long) As IntPtr
    Private Declare Function GetSystemMenu Lib "user32" (ByVal hWnd As IntPtr, ByVal bRevert As Boolean) As IntPtr
    Private Declare Function GetMenuItemCount Lib "user32" (ByVal hMenu As IntPtr) As Integer
    Private Declare Function DrawMenuBar Lib "user32" (ByVal hwnd As IntPtr) As Boolean

    Private Const MF_BYPOSITION = &H400
    Private Const MF_REMOVE = &H1000
    Private Const MF_DISABLED = &H2

    Public Sub DisableCloseButton(ByVal hwnd As IntPtr)
    Dim hMenu As IntPtr
    Dim menuItemCount As Integer

    hMenu = GetSystemMenu(hwnd, False)
    menuItemCount = GetMenuItemCount(hMenu)

    Call RemoveMenu(hMenu, menuItemCount - 1, _
    MF_DISABLED Or MF_BYPOSITION)

    Call RemoveMenu(hMenu, menuItemCount - 2, _
    MF_DISABLED Or MF_BYPOSITION)

    Call DrawMenuBar(hwnd)
    End Sub
    [/highlight]

    Add this to the event that will trigger the disable
    Ex: Form Load, Setting , Menu Item , etc...
    [highlight=vbnet]
    DisableCloseButton(Me.Handle)
    [/highlight]

    Fade Out

    This goes in a Non-Class are

    [highlight=vbnet]
    Friend WithEvents fader As System.Windows.Forms.Timer
    [/highlight]

    Call this to fade out

    [highlight=vbnet]
    Public Sub fade()
    Me.fader = New System.Windows.Forms.Timer
    Me.fader.Enabled = True
    Me.fader.Interval = 30
    End Sub
    [/highlight]

    This is the actual fade

    [highlight=vbnet]
    Private Sub fader_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles fader.Tick

    Me.Opacity -= 0.03 ('3% opacity, you can use anything youlike)

    ' this checks the opacity, it it is less then 5 then..end
    ' alot of people use 0, but I am doing it by 3% not by 1% , so check and ' see if it is less then 5 as opposed to = 0, however you can use any ' ' method you perfer, I just perfer this way (looks cleaner to me)
    If Me.Opacity < 2 Then
    End
    End If
    End Sub
    [/highlight]

    Make form transparent while dragging
    (this is and example of how checking the state of a mouse click can come in handy[above])

    [highlight=vbnet]
    Private Const WM_NCLBUTTONDOWN As Long = &HA1
    Private Const WM_NCLBUTTONUP As Long = &HA0
    Private Const WM_MOVING As Long = &H216
    Private Const WM_SIZE As Long = &H5
    Protected Overrides Sub DefWndProc(ByRef m As System.Windows.Forms.Message)
    Static LButtonDown As Boolean
    (checks left click)
    If CLng(m.Msg) = WM_NCLBUTTONDOWN Then
    '(as long as left button is down LButtonDown returns true)
    LButtonDown = True
    ElseIf CLng(m.Msg) = WM_NCLBUTTONUP Then
    ' (As long as left button is up, LButtonDown returns false)
    LButtonDown = False
    End If
    If LButtonDown Then
    If CLng(m.Msg) = WM_MOVING Then
    'Changes form opacity to 70% if the form is being dragged
    ' You can change the 0.7 to anything 0.1 = 10% 0.2 = 20 % and so on
    If Me.Opacity <> 0.9 Then Me.Opacity = 0.5
    ElseIf CLng(m.Msg) = WM_SIZE Then
    'Set the forms opacity to 60% if user is resizing the window
    If Me.Opacity <> 0.6 Then Me.Opacity = 0.6
    End If
    ElseIf Not LButtonDown Then
    If Me.Opacity <> 1.0 Then Me.Opacity = 1.0
    End If
    MyBase.DefWndProc(m)
    End Sub
    [/highlight]

    Windows Shadow - (Tested in Xp)

    [highlight=vbnet]
    Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
    Get
    Const CS_DROPSHADOW = &H20000
    Dim CrPa As CreateParams = MyBase.CreateParams
    CrPa.ClassStyle = CrPa.ClassStyle Or CS_DROPSHADOW
    Return CrPa
    End Get
    End Property
    [/highlight]

    [FONT="Times New Roman"][COLOR="DarkOliveGreen"]Snippets Part 3
    I will Be adding more as I write them

    Empty Recycling Bin

    Declarations And Variables

    [highlight=vbnet]
    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
    [/highlight]

    Empty Recycling Bin Sub
    [highlight=vbnet]
    Private Sub takeoutthetrash()
    SHEmptyRecycleBin(Me.Handle.ToInt32, vbNullString, SHERB_NOCONFIRMATION + SHERB_NOSOUND)
    SHUpdateRecycleBinIcon()
    End Sub
    [/highlight]

    Code to call the empty recycling bin sub

    [highlight=vbnet]
    takeoutthetrash()
    [/highlight]


    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

    [highlight=vbnet]
    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
    [/highlight]

    Get Hardware Serial

    Create a New Class and add this code

    [highlight=vbnet]
    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
    [/highlight]

    Now Add a textbox to your form, set it to multiline=true

    View Code

    In the namespace

    [highlight=vbnet]
    Imports System
    Imports System.Collections
    Imports System.Management
    [/highlight]

    Variables and Declarations

    'Dim appname as system.STATthreadattribute()
    Dim WindowsApplication1 As System.STAThreadAttribute()

    In Form1 Load add

    [highlight=vbnet]
    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
    [/highlight]

    Clear All Controls in a Form (MSDN Standard CODE)

    [highlight=vbnet]

    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
    [/highlight]

    Read File Content

    [highlight=vbnet]

    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
    [/highlight]

    To Call it Use

    ReadFileContent ("File Location")

    Get File Extension

    [highlight=vbnet]

    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
    [/highlight]

    To use Call the Function

    GetExtension ("File Location and Name")

    Prevent Pasting in a Textbox with Ctrl + V

    [highlight=vbnet]

    ' 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

    [/highlight]

    Random Password String From GUID

    [highlight=vbnet]

    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
    [/highlight]

    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

    [highlight=vbnet]


    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
    [/highlight]

    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

    [highlight=vbnet]
    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

    [highlight=vbnet]
    <?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>
    [/highlight]

    The information is as follows

    requireAdministrator:
    highestAvailable:
    asInvoker: Vb.net Default

    So for this particular case it would be

    [highlight=vbnet]
    <?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>
    [/highlight]

    Change Background Color of Form with Color Dialog

    Add a Color Dialog Box to your Form
    Add a button

    on button click Event

    [highlight=vbnet]

    Dim Bcolor As New ColorDialog()
    Bcolor.ShowDialog()
    Me.BackColor = Bcolor.Color
    [/highlight]

    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


    [highlight=vbnet]

    PrintDocument1.PrinterSettings.Copies = 1
    PrintDocument1.Print()
    [/highlight]

    Then Add this

    [highlight=vbnet]

    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
    [/highlight]

    Here is how to Create your own sleep method which will pause what you want to pause, but still allow the application to function

    [highlight=vbnet]

    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

    [/highlight]

    Note: the Application.DoEvents Will allow your application to function normally during sleep


    Now you can call a "proper" Sleep

    [highlight=vbnet]
    Sleep(time to sleep)
    [/highlight]


    Changing XML Node Values


    [highlight=vbnet]
    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")
    [/highlight]
    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
    [highlight=vbnet]
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    CheckedListBox1.Items.Add(TextBox1.Text)
    End Sub
    [/highlight]

    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
    [highlight=vbnet]
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    SaveCBox(CheckedListBox1)
    End Sub
    [/highlight]

    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

    [highlight=vbnet]
    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
    [/highlight]

    Run Application from Resources

    Name Space
    [highlight=vbnet]
    Imports System****
    [/highlight]

    Now this in a button click (or whet ever triggers the event)

    [highlight=vbnet]
    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)
    [/highlight]

    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

    [highlight=vbnet]
    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)
    [/highlight]


    Opening and saving .txt files
    https://www.mpgh.net/forum/33-visual-...-text-tut.html


    Using SAPI/Making your computer "Speak":
    https://www.mpgh.net/forum/33-visual-...uter-talk.html


    Last edited by NextGen1; 02-03-2011 at 01:00 PM. Reason: Organizing, Fixing mistakes In <<<<@>>>>, blocked for some reason


     


     


     



    The Most complete application MPGH will ever offer - 68%




  2. The Following 34 Users Say Thank You to NextGen1 For This Useful Post:

    ♪~ ᕕ(ᐛ)ᕗ (08-01-2010),aidandabest09 (11-24-2010),Ali (06-23-2010),AndrewxXx (09-20-2011),biohazardzz (06-29-2011),Blubb1337 (03-04-2010),cgallagher21 (09-06-2010),chikencow (02-11-2011),FlashDrive (03-04-2010),FUKO (10-21-2011),gunman353 (09-08-2012),hopefordope (05-03-2010),Katie_Perry (07-27-2010),Lolland (03-04-2010),matjuh123 (04-24-2010),MJLover (03-05-2010),mnpeepno2 (03-05-2010),nathanael890 (04-05-2010),nepito (03-13-2010),Nitehawk772 Bkup (10-10-2011),Opim10 (06-18-2013),poneboy00 (03-07-2010),Renamon Toast Crunch (06-10-2013),samerlol (06-28-2013),Sketchy (05-04-2011),skiiiz (03-13-2010),Sneakzy (05-09-2010),tempta43 (04-15-2010),Tony Stark` (02-09-2011),why06 (03-20-2010),zJester (09-03-2014),zmansquared (03-07-2010),Zoee (04-01-2014),Zoom (03-07-2010)

  3. #2
    NextGen1's Avatar
    Join Date
    Dec 2009
    Gender
    male
    Location
    Not sure really.
    Posts
    6,312
    Reputation
    382
    Thanks
    3,019
    My Mood
    Amazed

    Visual Basic Code Snippers [Shell Commands]

    Visual Basic .Net RunDll32 Commands


    Display the BlueScreen Of Death

    [highlight=vbnet]Shell ("rundll32 user,disableoemlayer")[/highlight]

    'Open Control Panel

    [highlight=vbnet]Shell("rundll32.exe shell32.dll Control_RunDLL")[/highlight]

    'Add Or Remove Programs

    [highlight=vbnet]Shell("rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,1")[/highlight]

    'Turn Off Computer

    [highlight=vbnet]Shell ("Rundll32.exe user32.dll,LockWorkStation")[/highlight]

    'Load Mouse Properties

    [highlight=vbnet]Shell ("Rundll32.exe shell32.dll,Control_RunDLL main.cpl @0")[/highlight]

    'Keyboard Properties

    [highlight=vbnet]Shell("Rundll32.exe shell32.dll,Control_RunDLL main.cpl @1")
    [/highlight]
    'Printer Properties

    [highlight=vbnet]Shell( "Rundll32.exe shell32.dll,Control_RunDLL main.cpl @2")[/highlight]

    'Fonts Folder

    [highlight=vbnet]Shell ("Rundll32.exe shell32.dll,Control_RunDLL main.cpl @3")[/highlight]

    'Internet Properties

    [highlight=vbnet]Shell ("rundll32.exe shell32.dll,Control_RunDLL inetcpl.cpl,,5")[/highlight]

    'Keyboard Accessibility

    [highlight=vbnet]Shell ("rundll32.exe shell32.dll,Control_RunDLL access.cpl,,1")[/highlight]

    'Sound / Accessibility

    [highlight=vbnet]Shell("rundll32.exe shell32.dll,Control_RunDLL access.cpl,,2")[/highlight]

    Display Accessibility

    [highlight=vbnet]Shell ("rundll32.exe shell32.dll,Control_RunDLL access.cpl,,3")[/highlight]

    'Display Settings

    [highlight=vbnet]Shell ("rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,0")[/highlight]

    Screen Saver

    [highlight=vbnet]Shell("rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,1")[/highlight]

    Internet Security

    [highlight=vbnet]Shell ("rundll32.exe shell32.dll,Control_RunDLL inetcpl.cpl,,1")[/highlight]

    Display Properties Window

    [highlight=vbnet]Shell("rundll32.exe shell32.dll,Control_RunDLL desk.cpl")[/highlight]

    Networking

    [highlight=vbnet]Shell ("rundll32.exe shell32.dll,Control_RunDLL netcpl.cpl")[/highlight]

    System Properties

    [highlight=vbnet]Shell ("rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl")[/highlight]

    Lock the Keyboard

    [highlight=vbnet]Shell ("rundll32.exe keyboard,disable")[/highlight]

    Disable the Mouse

    [highlight=vbnet]Shell ("rundll32.exe mouse,disable")[/highlight]

    Swap Mouse Buttons (left = right and vice Versa )

    [highlight=vbnet]Shell ("rundll32.exe user.dll,swapmousebutton")[/highlight]

    Shut Down Computer

    [highlight=vbnet]Shell ("rundll32.exe shell32.exe,SHExitWindowsEx 1")[/highlight]

    Log Off

    [highlight=vbnet]Shell ("rundll32.exe shell32.exe,SHExitWindowsEx 0")[/highlight]
    Last edited by NextGen1; 02-03-2011 at 01:02 PM.


     


     


     



    The Most complete application MPGH will ever offer - 68%




  4. The Following 18 Users Say Thank You to NextGen1 For This Useful Post:

    ♪~ ᕕ(ᐛ)ᕗ (08-01-2010),AndrewxXx (09-20-2011),biohazardzz (06-29-2011),Blubb1337 (03-12-2010),cgallagher21 (09-06-2010),deadskulzz (04-17-2011),Decreased (08-05-2010),hopefordope (05-03-2010),icebolt900 (11-19-2014),Katie_Perry (07-27-2010),MJLover (03-12-2010),mr farouk (02-01-2012),Ninja® (09-12-2011),Sketchy (04-28-2011),tempta43 (04-15-2010),tinnetju (05-26-2014),Tony Stark` (02-17-2011),why06 (03-20-2010)

  5. #3
    NextGen1's Avatar
    Join Date
    Dec 2009
    Gender
    male
    Location
    Not sure really.
    Posts
    6,312
    Reputation
    382
    Thanks
    3,019
    My Mood
    Amazed

    Post

    Multi Key [Example Ctrl + P]

    If you want to make a Ctrl+P Do something then..

    In KeyUp Sub of your form

    [highlight=vbnet]
    If e.Control = True And e.KeyCode = Keys.P Then
    Msgbox ("You pressed Ctrl + P") ' Anything you want here
    End If
    [/highlight]

    Connect to a Access Database
    'This one has been asked alot today

    NameSpace

    [highlight=vbnet]
    imports system.data.oledb
    [/highlight]

    [highlight=vbnet]
    Dim conn As New OleDbConnection
    conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data SourceDataDirectory|Data.mdb;Persist Security Info=True"
    conn.Open()
    ' conn.Close() 'Closes database
    'Which you can do immediately,
    [/highlight]

    This method can be applied to numerous database types, The connection string will have to be modified.

    SQL Server

    [highlight=vbnet]
    Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
    [/highlight]

    Oracle Database

    [highlight=vbnet]
    Data Source=TORCL;User Id=myUsername;Password=myPassword;
    [/highlight]

    Excel

    [highlight=vbnet]
    Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";
    [/highlight]

    Access

    [highlight=vbnet]
    Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=;
    [/highlight]

    Text File

    [highlight=vbnet]
    Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\txtFilesFolder\;Extended Properties="text;HDR=Yes;FMT=Delimited";
    [/highlight]

    Check List Box For Item

    [highlight=vbnet]
    Public Function inList(list As listbox, item As String) as Boolean
    Dim i As Long

    For i = 0 To list.ListCount - 1
    If (list.ItemData(i) = item) Then
    inlist = True
    Exit Function
    End If
    Next i

    inlist = False
    End Function
    [/highlight]

    to user it

    [highlight=vbnet]
    inlist(listbox , text to look for)
    [/highlight]


    Random Alphanumeric String

    [highlight=vbnet]
    Public Function RS(ByVal intLength As Integer, Optional ByVal strAllowedCharacters As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ0123456789")
    Randomize()
    Dim chrC() As Char = strAllowedCharacters.ToCharArray
    Dim strR As New StringBuilder
    Dim grtR As New Random
    Do Until Len(strR.ToString) = intLength
    Dim x As Integer = Rnd() * (chrC.Length - 1)
    strR.Append(chrC(CInt(x)))
    Loop
    Return strR.ToString
    End Function
    [/highlight]

    You will need to imports system.text and system.drawing

    To use the code it is

    rs(number of characters to generate)

    Example:

    [highlight=vbnet]
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    TextBox1.Text = RS(20)

    End Sub

    Public Function RS(ByVal intLength As Integer, Optional ByVal strAllowedCharacters As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ0123456789")
    Randomize()
    Dim chrC() As Char = strAllowedCharacters.ToCharArray
    Dim strR As New StringBuilder
    Dim grtR As New Random
    Do Until Len(strR.ToString) = intLength
    Dim x As Integer = Rnd() * (chrC.Length - 1)
    strR.Append(chrC(CInt(x)))
    Loop
    Return strR.ToString
    End Function
    [/highlight]

    Activate a Running Process By Name

    [highlight=vbnet]
    AppActivate("Untitled - Notepad")
    [/highlight]

    Activate Running Process by id

    [highlight=vbnet]
    Dim processID As Integer

    processID = Shell("NOTEPAD.EXE", AppWinStyle.NormalFocus)

    AppActivate(processID)
    [/highlight]

    SendKeys To application

    [highlight=vbnet]
    SendKeys.SendWait("{ENTER}")
    [/highlight]

    Write to application log file.

    [highlight=vbnet]
    My.Application.Log.WriteEntry("Entry Here")
    [/highlight]

    Define a Structure

    [highlight=vbnet]
    Structure MyStructure
    Public ValueOne As Integer
    Public ValueTwo As Boolean
    End Structure
    [/highlight]

    Sound

    Loop a Sound

    [highlight=vbnet]
    My.Computer.Audio.Play("SoundFile.wav", AudioPlayMode.BackgroundLoop)
    [/highlight]

    Play Sound

    [highlight=vbnet]
    My.Computer.Audio.Play("ringout.wav", AudioPlayMode.WaitToComplete)
    [/highlight]

    Stop Playing Sound

    [highlight=vbnet]
    My.Computer.Audio.Stop()

    [/highlight]



    Last edited by NextGen1; 02-03-2011 at 01:05 PM.


     


     


     



    The Most complete application MPGH will ever offer - 68%




  6. The Following 12 Users Say Thank You to NextGen1 For This Useful Post:

    ♪~ ᕕ(ᐛ)ᕗ (08-01-2010),biohazardzz (06-29-2011),cgallagher21 (09-06-2010),House (11-30-2010),Katie_Perry (07-27-2010),Ninja® (09-12-2011),noob555 (04-12-2010),Sketchy (05-04-2011),tempta43 (04-15-2010),Tony Stark` (02-17-2011),why06 (03-20-2010),williamph (11-16-2010)

  7. #4
    NextGen1's Avatar
    Join Date
    Dec 2009
    Gender
    male
    Location
    Not sure really.
    Posts
    6,312
    Reputation
    382
    Thanks
    3,019
    My Mood
    Amazed
    As requested, XML

    Imports

    [highlight=vbnet]
    Imports System.Xml
    Imports System.Xml.Schema
    Imports System.Xml.XPath
    [/highlight]


    Query in XML

    [highlight=vbnet]
    Dim y = <Root>
    <%= From i In "abc" _
    Where i = "b" _
    Select <Result>
    <%= i %>
    </Result> _
    %>
    </Root>
    [/highlight]


    Create Schema for XMl

    [highlight=vbnet]

    Dim infer = New XmlSchemaInference()
    Dim sc = New XmlSchemaSet()
    sc = infer.InferSchema(New XmlTextReader("sample.xml"))

    Dim w = XmlWriter.Create(New StreamWriter("sampleSchema.xsd"))
    For Each schemafile In sc.Schemas()
    schemafile.Write(w)
    Next
    [/highlight]


    _________________

    Resize a button dynamically based on text

    [highlight=vbnet]
    ' 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)
    [/highlight]

    Create a Pen

    [highlight=vbnet]
    Dim myPen As System.Drawing.Pen
    myPen = New System.Drawing.Pen(Color.Black)
    [/highlight]

    Display a animated Gif

    [highlight=vbnet]
    PictureBox1.Image() = Image.FromFile("gifname.gif")
    [/highlight]

    _______________

    Convert Mouse Coordinates to screen coordinates

    [highlight=vbnet]
    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
    [/highlight]

    Create a Transparent form

    [highlight=vbnet]
    frmTransparentForm.Opacity = 0.90
    [/highlight]

    Determine modifier key pressed

    [highlight=vbnet]
    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
    [/highlight]

    Remove Title Bar

    [highlight=vbnet]
    Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
    [/highlight]


    Create Email Message

    [highlight=vbnet]
    Dim message As New MailMessage("sender@address", "from@address", "Subject", "Message Text")
    Dim emailClient As New SmtpClient("Email Server Name")
    emailClient.Send(message)
    [/highlight]

    Use Serial Port To Dial A Number

    [highlight=vbnet]

    Using comPort As SerialPort = My.Computer.Ports.OpenSerialPort("COM1", 2400)
    comPort.DtrEnable = True
    comPort.Write("555-555-5455" & vbCrLf)


    End Using
    [/highlight]


    ____________


    Search Files for an expression

    [highlight=vbnet]
    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")
    [/highlight]

    _________________________________

    A more advanced basic spammer

    Add 2 Text boxes and one button

    Name Space
    - I notated everything

    [highlight=vbnet]
    'Used to import COM and Invoke services , needed for DLL Import
    Imports System****ntime.InteropServices
    [/highlight]

    Functions (just below public call formname

    [highlight=vbnet]
    ' 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
    [/highlight]

    and below that

    [highlight=vbnet]
    ' 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
    [/highlight]

    On the button click event

    [highlight=vbnet]
    ' 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
    [/highlight]


    Last edited by NextGen1; 02-03-2011 at 01:06 PM.


     


     


     



    The Most complete application MPGH will ever offer - 68%




  8. The Following 15 Users Say Thank You to NextGen1 For This Useful Post:

    .:Kikko:. (08-02-2011),biohazardzz (06-29-2011),cgallagher21 (09-06-2010),Katie_Perry (07-27-2010),mexicano007 (04-24-2010),Ninja® (09-12-2011),noob555 (04-12-2010),Sketchy (05-04-2011),tempta43 (04-15-2010),Tony Stark` (02-17-2011),War3Cadu (09-15-2010),why06 (03-20-2010),williamph (11-16-2010),Zoom (03-20-2010),[color=red]FHB[/color] (09-25-2010)

  9. #5
    Samueldo's Avatar
    Join Date
    Jan 2010
    Gender
    male
    Location
    Meh
    Posts
    1,023
    Reputation
    29
    Thanks
    348
    My Mood
    Inspired
    Here's a simple but useful one. These are 2 easy ways to convert a color from a string.

    [highlight=vbnet]Color.FromName("Blue") 'Whatever color name you want in those brackets

    Color.FromArgb(red value, green value, blue value) 'You could you strings or integers here[/highlight]
    Last edited by NextGen1; 02-03-2011 at 01:09 PM.
    Quote Originally Posted by Grim View Post
    glad to be an inspiration
    Minions rule. /endof

    InjectPlz Refresh - download v1.0 now!

  10. The Following User Says Thank You to Samueldo For This Useful Post:

    Ninja® (09-12-2011)

  11. #6
    Blubb1337's Avatar
    Join Date
    Sep 2009
    Gender
    male
    Location
    Germany
    Posts
    5,915
    Reputation
    161
    Thanks
    3,108
    I wrote up this little configureable function to read between strings.

    [highlight=vbnet]Imports System.IO
    Imports System.Text[/highlight]

    [highlight=vbnet] Public Function rb(ByVal readfrom As String, ByVal startstring As String, ByVal str1 As String, ByVal str2 As String)
    Dim writeto As String
    Dim s As New MemoryStream(Encoding.ASCII.GetBytes(readfrom))

    Dim reader As New IO.StreamReader(s)

    While Not reader.EndOfStream

    writeto = reader.ReadLine()

    If writeto.StartsWith(startstring) Then

    Dim x1 As Integer = writeto.IndexOf(str1) + (str1.Length + 1)
    Dim x2 As Integer = writeto.IndexOf(str2, x1) + 1

    Dim result As String = Mid(writeto, x1, x2 - x1)

    Return result

    End If


    End While

    End Function[/highlight]

    I.E. a youtube video...

    <strong class="watch-view-count">301</strong>
    Textbox1.Text = the document text of the youtube video

    [highlight=vbnet]Dim views as string = rb(Textbox1.Text, "<strong class="watch-view-count">", "<strong class="watch-view-count">", "</strong>")[/highlight]

    The 'startstring' thingy is optional but may come in handy in more complex strings :P.
    Last edited by NextGen1; 02-03-2011 at 01:14 PM.



  12. The Following 5 Users Say Thank You to Blubb1337 For This Useful Post:

    biohazardzz (06-29-2011),cgallagher21 (09-06-2010),K4GE (08-07-2010),Ninja® (09-12-2011),Tony Stark` (02-17-2011)

  13. #7
    NovaSynth's Avatar
    Join Date
    Jan 2010
    Gender
    male
    Posts
    14
    Reputation
    10
    Thanks
    10

    Memory Editing [vb6]

    This is my memory editing snippet. Just place this code inside a module and use it in your programs if you wish Unfortunatly, i had coded this module in vb6, so not every command will work with vb.net. You may translate if you wish, i just ask that you re-post for others to use.


    ~~~~~Declarations~~~~~
    [highlight=vbnet] Public Const PROCESS_ALL_ACCESS = &H1F0FFF
    Dim f1holder As Integer
    Dim timer_pos As Long
    Dim hProcess As Long

    Public Declare Function GetWindowThreadProcessId Lib "user32" (ByVal SomeValueIsStoredHere As Long, ByVal lpdwProcessId As Long) As Long
    Public Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
    Public Declare Function WriteProcessMemory Lib "kernel32" (ByVal hProcess As Long, ByVal lpBaseAddress As Object, ByVal lpBuffer As Object, ByVal nSize As Long, ByVal lpNumberOfBytesWritten As Long) As Long
    Public Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
    Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal Classname As String, ByVal WindowName As String) As Long
    Public Declare Function GetKeyPress Lib "user32" Alias "GetAsyncKeyState" (ByVal key As Long) As Integer
    Public Declare Function ReadProcessMem Lib "kernel32" Alias "ReadProcessMemory" (ByVal hProcess As Long, ByVal lpBaseAddress As Object, ByRef lpBuffer As Object, ByVal nSize As Long, ByVal lpNumberOfBytesWritten As Long) As Long[/highlight]


    ~~~~~Module~~~~~
    [highlight=vbnet] Public Function WriteALong(ByVal TheGame As String, ByVal TheAddress As Long, ByVal ThisIsTheValue As Long)
    Dim SomeValueIsStoredHere As Long
    Dim SomeValueIsStoredHereToo As Long
    Dim SomeValue As Long
    SomeValueIsStoredHere = FindWindow(vbNullString, TheGame)
    GetWindowThreadProcessId(SomeValueIsStoredHere, SomeValueIsStoredHereToo)
    SomeValue = OpenProcess(PROCESS_ALL_ACCESS, False, SomeValueIsStoredHereToo)
    If (SomeValue = 0) Then
    Exit Function
    End If
    WriteProcessMemory(SomeValue, TheAddress, ThisIsTheValue, 4, 0&)
    CloseHandle(hProcess)
    End Function[/highlight]
    [highlight=vbnet] Public Function ReadALong(ByVal TheGame As String, ByVal TheAddress As Long, ByVal TheValue As Long)
    Dim SomeValueIsStoredHere As Long
    Dim SomeValueIsStoredHereToo As Long
    Dim SomeValue As Long
    SomeValueIsStoredHere = FindWindow(vbNullString, TheGame)
    GetWindowThreadProcessId(SomeValueIsStoredHere, SomeValueIsStoredHereToo)
    SomeValue = OpenProcess(PROCESS_ALL_ACCESS, False, SomeValueIsStoredHereToo)
    If (SomeValue = 0) Then
    Exit Function
    End If
    ReadProcessMem(SomeValue, TheAddress, TheValue, 4, 0&)
    CloseHandle(hProcess)
    End Function[/highlight]
    [highlight=vbnet] Public Function ReadAFloat(ByVal TheGame As String, ByVal TheAddress As Long, ByVal TheValue As Single)
    Dim SomeValueIsStoredHere As Long
    Dim SomeValueIsStoredHereToo As Long
    Dim SomeValue As Long
    SomeValueIsStoredHere = FindWindow(vbNullString, TheGame)
    GetWindowThreadProcessId(SomeValueIsStoredHere, SomeValueIsStoredHereToo)
    SomeValue = OpenProcess(PROCESS_ALL_ACCESS, False, SomeValueIsStoredHereToo)
    If (SomeValue = 0) Then
    Exit Function
    End If
    ReadProcessMem(SomeValue, TheAddress, TheValue, 4, 0&)
    CloseHandle(hProcess)
    End Function[/highlight]
    [highlight=vbnet] Public Function WriteAFloat(ByVal TheGame As String, ByVal TheAddress As Long, ByVal ThisIsTheValue As Single)
    Dim SomeValueIsStoredHere As Long
    Dim SomeValueIsStoredHereToo As Long
    Dim SomeValue As Long
    SomeValueIsStoredHere = FindWindow(vbNullString, TheGame)
    GetWindowThreadProcessId(SomeValueIsStoredHere, SomeValueIsStoredHereToo)
    SomeValue = OpenProcess(PROCESS_ALL_ACCESS, False, SomeValueIsStoredHereToo)
    If (SomeValue = 0) Then
    Exit Function
    End If
    WriteProcessMemory(SomeValue, TheAddress, ThisIsTheValue, 4, 0&)
    CloseHandle(hProcess)
    End Function[/highlight]


    ~~~~~Instructions~~~~~
    Alright. In order for this to work, im gonna show you a quick example using that cheezy little Pinball game that comes with Windows XP.

    lets say we turned the game on and made a button that we set the button command to this: [highlight=vbnet]
    Private Sub Command1_Click()
    Call WriteALong("3D Pinball for Windows, Space Cadet", &HA12EF4, 999999)
    Call WriteALong("3D Pinball for Windows, Space Cadet", &HB8AEBA, 999999)
    End Sub
    [/highlight]

    Basically what the code means, is that i Called the function "WriteALong" from the module that is just above. "3D Pinball for Windows, Space Cadet" is the window title, &HB8AEBA is the address. "999999" is the value you set that specific address to.

    *Note: Add &H instead of the 2 00 (two zero's), Here's an example: Your address is 00L1FD4. You need to replace the 00 (two zero's) with an &H , then you would get this: &HL1FD4. If there is only 1 0 at the beginning then just replace it with an &. If there are no zero's at the beginning then this rule does not apply.


    And thats it!

    oh and p.s. This is basically how people use VB and make trainers for games and such.
    Last edited by NextGen1; 02-03-2011 at 02:12 PM.

  14. The Following 4 Users Say Thank You to NovaSynth For This Useful Post:

    biohazardzz (06-29-2011),Lyoto Machida (04-16-2011),Ninja® (09-12-2011),Tony Stark` (02-17-2011)

  15. #8
    wtfiwantthatname's Avatar
    Join Date
    Oct 2008
    Gender
    male
    Posts
    260
    Reputation
    10
    Thanks
    39
    My Mood
    Bored
    Here is a module with code for encrypting and decrypting strings.

    Code:
    Imports System.Security.Cryptography
    Module Encryption
        Public Function AESEncrypt(ByVal Key As String, ByVal Data As String) As String
            Try
                Dim AES As AesCryptoServiceProvider
                With AES
                    .Mode = CipherMode.ECB
                    .Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key)
                    .IV = .Key
                End With
                Dim AESEncryptor As ICryptoTransform = AES.CreateEncryptor
                Dim DataBuffer As Byte()
                Dim EncryptedData As Byte()
                DataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
                EncryptedData = AESEncryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return ByteToString(EncryptedData)
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
    
        Public Function AESEncrypt(ByVal Key() As Byte, ByVal Data() As Byte) As Byte()
            Try
                Dim AES As AesCryptoServiceProvider
                With AES
                    .Mode = CipherMode.ECB
                    .Key = Key
                    .IV = .Key
                End With
                Dim AESEncryptor As ICryptoTransform = AES.CreateEncryptor
                Dim DataBuffer As Byte()
                Dim EncryptedData As Byte()
                DataBuffer = Data
                EncryptedData = AESEncryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return EncryptedData
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
    
        Public Function AESDecrypt(ByVal Key() As Byte, ByVal Data() As Byte) As Byte()
            Try
                Dim AES As AesCryptoServiceProvider
                With AES
                    .Mode = CipherMode.ECB
                    .Key = Key
                    .IV = .Key
                End With
                Dim AESDecryptor As ICryptoTransform = AES.CreateDecryptor
                Dim DataBuffer As Byte()
                Dim DecryptedData As Byte()
                DataBuffer = Data
                DecryptedData = AESDecryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return DecryptedData
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
    
        Public Function AESDecrypt(ByVal Key As String, ByVal Data As String) As String
            Try
                Dim AES As AesCryptoServiceProvider
                With AES
                    .Mode = CipherMode.ECB
                    .Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key)
                    .IV = .Key
                End With
                Dim AESDecryptor As ICryptoTransform = AES.CreateDecryptor
                Dim DataBuffer As Byte()
                Dim DecryptedData As Byte()
                DataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
                DecryptedData = AESDecryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return ByteToString(DecryptedData)
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
    
        Public Function RC2Encrypt(ByVal Key As String, ByVal Data As String) As Byte()
            Try
                Dim RC2 As RC2CryptoServiceProvider
                With RC2
                    .Mode = CipherMode.ECB
                    .UseSalt = True
                    .Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key)
                    .IV = .Key
                End With
                Dim RC2Encryptor As ICryptoTransform = RC2.CreateEncryptor
                Dim databuffer As Byte()
                Dim EncryptedData As Byte()
                databuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
                EncryptedData = RC2Encryptor.TransformFinalBlock(databuffer, 0, databuffer.Length)
                Return EncryptedData
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
        Public Function RC2Encrypt(ByVal Key() As Byte, ByVal Data() As Byte) As Byte()
            Try
                Dim RC2 As RC2CryptoServiceProvider
                With RC2
                    .Mode = CipherMode.ECB
                    .UseSalt = True
                    .Key = Key
                    .IV = .Key
                End With
                Dim RC2Encryptor As ICryptoTransform = RC2.CreateEncryptor
                Dim databuffer As Byte()
                Dim EncryptedData As Byte()
                databuffer = Data
                EncryptedData = RC2Encryptor.TransformFinalBlock(databuffer, 0, databuffer.Length)
                Return EncryptedData
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
        Public Function RC2Decrypt(ByVal key() As Byte, ByVal data() As Byte) As Byte()
            Try
                Dim RC2 As RC2CryptoServiceProvider
                With RC2
                    .Mode = CipherMode.ECB
                    .UseSalt = True
                    .Key = key
                    .IV = .Key
                End With
                Dim RC2Decryptor As ICryptoTransform = RC2.CreateDecryptor
                Dim databuffer As Byte()
                Dim Decrypteddata As Byte()
                databuffer = data
                Decrypteddata = RC2Decryptor.TransformFinalBlock(databuffer, 0, databuffer.Length)
                Return Decrypteddata
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
        Public Function RC2Decrypt(ByVal Key As String, ByVal Data As String) As String
            Try
                Dim RC2 As RC2CryptoServiceProvider
                With RC2
                    .Mode = CipherMode.ECB
                    .UseSalt = True
                    .Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key)
                    .IV = .Key
                End With
                Dim RC2Decryptor As ICryptoTransform = RC2.CreateDecryptor
                Dim DataBuffer As Byte()
                Dim DecryptedData As Byte()
                DataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
                DecryptedData = RC2Decryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return ByteToString(DecryptedData)
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
        Public Function DESEncrypt(ByVal Key As String, ByVal Data As String) As String
            Try
                Dim DES As DESCryptoServiceProvider
                With DES
                    .Mode = CipherMode.ECB
                    .Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key)
                    .IV = .Key
                End With
                Dim DESEncryptor As ICryptoTransform = DES.CreateEncryptor
                Dim DataBuffer As Byte()
                Dim EncryptedData As Byte()
                DataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
                EncryptedData = DESEncryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return ByteToString(EncryptedData)
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
        Public Function DESEncrypt(ByVal key() As Byte, ByVal data() As Byte) As Byte()
            Try
                Dim DES As DESCryptoServiceProvider
                With DES
                    .Mode = CipherMode.ECB
                    .Key = key
                    .IV = .Key
                End With
                Dim DESEncryptor As ICryptoTransform = DES.CreateEncryptor
                Dim DataBuffer As Byte()
                Dim Encrypteddata As Byte()
                DataBuffer = data
                Encrypteddata = DESEncryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return Encrypteddata
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
    
    
        Public Function DESDecrypt(ByVal Key As String, ByVal Data As String) As String
            Try
                Dim DES As DESCryptoServiceProvider
                With DES
                    .Mode = CipherMode.ECB
                    .Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key)
                    .IV = .Key
                End With
                Dim DESDecryptor As ICryptoTransform = DES.CreateDecryptor
                Dim DataBuffer As Byte()
                Dim DecryptedData As Byte()
                DataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
                DecryptedData = DESDecryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return ByteToString(DecryptedData)
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
        Public Function DESDecrypt(ByVal Key() As Byte, ByVal data() As Byte) As Byte()
            Try
                Dim DES As DESCryptoServiceProvider
                With DES
                    .Mode = CipherMode.ECB
                    .Key = Key
                    .IV = .Key
                End With
                Dim DESDecryptor As ICryptoTransform = DES.CreateDecryptor
                Dim DataBuffer As Byte()
                Dim DecryptedData As Byte()
                DataBuffer = data
                DecryptedData = DESDecryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return DecryptedData
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
        Public Function TripleDESEncrypt(ByVal Key As String, ByVal Data As String) As String
            Try
                Dim TripleDes As TripleDESCryptoServiceProvider
                With TripleDes
                    .Mode = CipherMode.ECB
                    .Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key)
                    .IV = .Key
                End With
                Dim TripleDESEncryptor As ICryptoTransform = TripleDes.CreateEncryptor
                Dim DataBuffer As Byte()
                Dim EncryptedData As Byte()
                DataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
                EncryptedData = TripleDESEncryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return ByteToString(EncryptedData)
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
        Public Function TripleDESEncrypt(ByVal key As Byte(), ByVal data As Byte()) As Byte()
            Try
                Dim TripleDes As TripleDESCryptoServiceProvider
                With TripleDes
                    .Mode = CipherMode.ECB
                    .Key = key
                    .IV = .Key
                End With
                Dim TripleDESEncryptor As ICryptoTransform = TripleDes.CreateEncryptor
                Dim DataBuffer As Byte()
                Dim EncryptedData As Byte()
                DataBuffer = data
                EncryptedData = TripleDESEncryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return EncryptedData
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
    
        Public Function TriplesDESDecrypt(ByVal key As Byte(), ByVal Data As Byte()) As Byte()
            Try
                Dim TripleDes As TripleDESCryptoServiceProvider
                With TripleDes
                    .Mode = CipherMode.ECB
                    .Key = key
                    .IV = .Key
                End With
                Dim TripleDESDecryptor As ICryptoTransform = TripleDes.CreateDecryptor
                Dim DataBuffer As Byte()
                Dim DecryptedData As Byte()
                DataBuffer = Data
                DecryptedData = TripleDESDecryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return DecryptedData
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
        Public Function TripleDESDecrypt(ByVal Key As String, ByVal Data As String) As String
            Try
                Dim TripleDes As TripleDESCryptoServiceProvider
                With TripleDes
                    .Mode = CipherMode.ECB
                    .Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key)
                    .IV = .Key
                End With
                Dim TripleDESDecryptor As ICryptoTransform = TripleDes.CreateDecryptor
                Dim DataBuffer As Byte()
                Dim DecryptedData As Byte()
                DataBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(Data)
                DecryptedData = TripleDESDecryptor.TransformFinalBlock(DataBuffer, 0, DataBuffer.Length)
                Return ByteToString(DecryptedData)
            Catch ex As Exception
                MessageBox.Show("The Following Error(s) occured: " & ex.Message, "Error", MessageBoxButtons.OK)
            End Try
        End Function
    
    
        Public Function ByteToString(ByVal Bytes As Byte()) As String
            Return Convert.ToString(Bytes)
        End Function
    End Module
    Here is another module. This time its for setting debug privileges in the case that you dont have them.
    Code:
    Module SetDebugPrivileges
        Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LUID) As Int32
        Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As Int32, ByVal DisableAllPrivileges As Int32, ByRef NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Int32, ByRef PreviousState As TOKEN_PRIVILEGES, ByRef ReturnLength As Int32) As Int32
        Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Int32, ByVal DesiredAccess As Int32, ByRef TokenHandle As Int32) As Int32
        Private Declare Function GetCurrentProcess Lib "kernel32.dll" () As Int32
    
        Private Const SE_DEBUG_NAME As String = "SeDebugPrivilege"
        Private Const TOKEN_ADJUST_PRIVILEGES As Int32 = &H20
        Private Const TOKEN_QUERY As Int32 = &H8
        Private Const SE_PRIVILEGE_ENABLED As Int32 = &H2
    
    
        Private Structure LUID
            Dim LowPart As Int32
            Dim HighPart As Int32
        End Structure
    
        Private Structure LUID_AND_ATTRIBUTES
            Dim pLuid As LUID
            Dim Attributes As Int32
        End Structure
    
        Private Structure TOKEN_PRIVILEGES
            Dim PrivilegeCount As Int32
            Dim TheLuid As LUID
            Dim Attributes As Int32
        End Structure
    
    
        Public Function LoadPrivilege(ByVal Privilege As String) As Boolean
            On Error GoTo ErrHandler
            Dim ProcHandle As Int32
            Dim htoken As Int32
            Dim tokenPrivileges As TOKEN_PRIVILEGES
            Dim SEDebugNameValue As LUID
            Dim tkpNewButIgnored As TOKEN_PRIVILEGES
    
            ProcHandle = GetCurrentProcess()
            OpenProcessToken(ProcHandle, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, htoken)
            LookupPrivilegeValue("", Privilege, SEDebugNameValue)
            With tokenPrivileges
                .PrivilegeCount = 1
                .TheLuid = SEDebugNameValue
                .Attributes = SE_PRIVILEGE_ENABLED
            End With
            AdjustTokenPrivileges(htoken, False, tokenPrivileges, Len(tokenPrivileges), tkpNewButIgnored, Nothing)
            Return True
            Exit Function
    ErrHandler:
            Return False
        End Function
    
    End Module
    And here is a module for DLL injection on 32-Bit OS's
    Code:
    Module InjLib
    
        'CreateRemoteThread for calling loadlibrary in the target process address space to load our Dll
        Private Declare Function CreateRemoteThread Lib "kernel32.dll" (ByVal hProcess As Int32, ByVal lpThreadAttributes As Int32, ByVal dwStackSize As Int32, ByVal lpStartAddress As Int32, ByVal lpParameter As Int32, ByVal dwCreationFlags As Int32, ByRef lpThreadId As Int32) As Int32
        'VirtualAllocEx to allocate space in our target process so that we can write the path to our Dll
        Private Declare Function VirtualAllocEx Lib "kernel32.dll" (ByVal hProcess As Int32, ByVal lpAddress As Int32, ByVal dwSize As Int32, ByVal flAllocationType As Int32, ByVal flProtect As Int32) As Int32
        'WriteProcessMemory to write the path to our Dll in the target process address space
        Private Declare Function WriteProcessMemory Lib "kernel32.dll" (ByVal hProcess As Int32, ByVal lpBaseAddress As Int32, ByVal lpBuffer As String, ByVal nSize As Int32, ByRef lpNumberOfBytesWritten As Int32) As Int32
        'VirtualFreeEx to clean up when done
        Private Declare Function VirtualFreeEx Lib "kernel32.dll" (ByVal hProcess As Int32, ByVal lpAddress As Int32, ByRef dwSize As Int32, ByVal dwFreeType As Int32) As Int32
        'Get ModuleHandle to get a handle to LoadLibrary so we can use the Handle to get its Address in the target Process' space
        Private Declare Function GetModuleHandle Lib "kernel32.dll" Alias "GetModuleHandleA" (ByVal lpModuleName As String) As Int32
        'GetProcAddress to get the address that LoadLibraryA resides at
        Private Declare Function GetProcAddress Lib "kernel32.dll" (ByVal hModule As Int32, ByVal lpProcName As String) As Int32
        'OpenProcess to get a handle to our target process and open it with the rights we require
        Private Declare Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccess As Int32, ByVal bInheritHandle As Int32, ByVal dwProcessId As Int32) As Int32
        'CloseHandle to Close all open handles we needed
        Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Int32) As Int32
    
    
        Private Const Create_Suspended As Int32 = &H4 'To freeze process when we call createremotethread
        Private Const process_vm_operation As Int32 = &H8 ' Access Rights
        Private Const process_create_thread As Int32 = &H2
        Private Const process_suspend_resume As Int32 = &H800 
        Private Const process_vm_write As Int32 = &H20 ' Access Rights 
        Private Const process_vm_read As Int32 = &H10 ' Access Rights
        Private Const mem_commit As Int32 = &H1000 ' What to do with memory from VirtualallocEx
        Private Const mem_release As Int32 = &H8000 ' Tells the Computer to free memory when called with VirtualFree
        Private Const page_readwrite As Int32 = &H4 
    
    
        Private Access As Int32 = process_vm_read Or process_vm_write Or process_vm_operation Or process_create_thread
    
        Public Function InjectDlls(ByVal ProcessName As String, ByVal DllPaths() As String) As int32
            Dim ProcHandle As Int32 ' Handle to Target Process
            Dim DllVirtLoc As Int32 ' Address of Dll Path
            Dim Inject As Int32     ' Error Checking
            Dim CreateThread As Int32 ' Error Checking
            Dim ThreadID As Int32   ' Handle to our Created Thread
            Dim MHandle As Int32    ' Handle to Kernel32.dll
            Dim i As Int32          ' Counter
            Dim TargetProc As Process() = Process.GetProcessesByName(ProcessName) ' Gets Process info
    
            MHandle = GetModuleHandle("Kernel32.dll") ' Gets Handle to Kernel32.dll
            If MHandle = 0 Then
                MessageBox.Show("Could not get a handle to Kernel32.dll", "Error", MessageBoxButtons.OK)
                Return 0
                Exit Function
            Else
                ProcHandle = OpenProcess(Access, 0, TargetProc(0).Id) ' Gets Handle to Process and opens with our desired rights
                If ProcHandle = 0 Then
                    MessageBox.Show("Could not get a handle to Target process", "Error", MessageBoxButtons.OK)
                    CloseHandle(MHandle) ' Closes handle to kernel32.dll because we could not open our target process
                    Return 0
                    Exit Function
                Else
                    For i = 0 To UBound(DllPaths) - 1
                        System.Threading.Thread.Sleep(100) ' Our Delay for initial Injection and subsequent injection
                        DllVirtLoc = VirtualAllocEx(ProcHandle, 0, DllPaths(i), mem_commit, page_readwrite) ' Allocates Space in Target Address Space
                        If DllVirtLoc = 0 Then
                            MessageBox.Show("Could not allocate space in target process", "Error", MessageBoxButtons.OK)
                            CloseHandle(MHandle) ' Closes Handle to Kernel32.dll because we could not allocate space
                            CloseHandle(ProcHandle) ' Closes Handle to Process becausewe could not allocate the space
                        Else
                            Inject = WriteProcessMemory(ProcHandle, DllVirtLoc, DllPaths(i), DllPaths(i).Length + 1, Nothing) ' Writes our Dll's path to Targets Address Space
                            If Inject = 0 Then
                                MessageBox.Show("Could not write to process' address space", "Error", MessageBoxButtons.OK)
                                VirtualFreeEx(ProcHandle, DllVirtLoc, 0, mem_release) ' Free Allocated Space because writing failed
                                CloseHandle(MHandle) ' Close handle to kernel32.dll because writing failed
                                CloseHandle(ProcHandle) ' Close Handle to Process because writing failed
                            Else
                                CreateThread = CreateRemoteThread(ProcHandle, 0, 0, GetProcAddress(MHandle, "LoadLibraryA"), DllVirtLoc, 0, ThreadID)
                                If CreateThread = 0 Then
                                    MessageBox.Show("Could not create remote thread", "Error", MessageBoxButtons.OK)
                                    VirtualFreeEx(ProcHandle, DllVirtLoc, 0, mem_release) ' Frees Allocated space because we could not create our remote thread
                                    CloseHandle(MHandle) ' Closes Handle to Kernel32.dll because we could not create our remote thread
                                    CloseHandle(ProcHandle) ' Closes Handle to Target Process because we could not create our remote thread
                                    Return 0
                                    Exit Function
                                Else
                                    VirtualFreeEx(ProcHandle, DllVirtLoc, 0, mem_release) ' Frees Allocated Space because we are done
                                End If
                            End If
                        End If
                        Return 1 ' Returns 1 for Success 0 for failure declare recieving variable as array
                    Next i
                    CloseHandle(MHandle) ' Close Handle to Kernel32.dll because we are done
                    CloseHandle(ProcHandle) ' Close Handle to Target Process because we are done
                End If
            End If
        End Function
    
    
    End Module
    Last edited by wtfiwantthatname; 06-09-2010 at 10:07 AM.
    "I don't believe in an afterlife, so I don't have to spend my whole life fearing hell, or fearing heaven even more. For whatever the tortures of hell, I think the boredom of heaven would be even worse." - Isaac Asimov

  16. The Following 3 Users Say Thank You to wtfiwantthatname For This Useful Post:

    biohazardzz (06-29-2011),Ninja® (09-12-2011),Tony Stark` (02-17-2011)

  17. #9
    Hassan's Avatar
    Join Date
    May 2010
    Gender
    male
    Location
    System.Threading.Tasks
    Posts
    4,764
    Reputation
    495
    Thanks
    2,133
    My Mood
    Dead
    Snap Form To Screen Borders:

    This feature allows you to drag your window near the screen border and have the window automatically get pulled towards that border like a magnet. It's Perry Marchant's implementation of VB.NET.

    ■ Import this namespace to the form:

    [highlight=vb.net]Imports system****ntime.InteropServices[/highlight]

    ■ Declare the following:

    [highlight=vb.net] Private Const mSnapOffset As Integer = 35
    Private Const WM_WINDOWPOSCHANGING As Integer = &H46

    <StructLayout(LayoutKind.Sequential)> _
    Public Structure WINDOWPOS
    Public hwnd As IntPtr
    Public hwndInsertAfter As IntPtr
    Public x As Integer
    Public y As Integer
    Public cx As Integer
    Public cy As Integer
    Public flags As Integer
    End Structure
    [/highlight]

    ■ After that add these sub-procedures to the program:
    [highlight=vb.net]Protected Overrides Sub WndProc(ByRef m As Message)
    ' Listen for operating system messages
    Select Case m.Msg
    Case WM_WINDOWPOSCHANGING
    SnapToDesktopBorder(Me, m.LParam, 0)
    End Select

    MyBase.WndProc(m)
    End Sub

    Public Shared Sub SnapToDesktopBorder(ByVal clientForm As Form, ByVal LParam As IntPtr, ByVal widthAdjustment As Integer)
    If clientForm Is Nothing Then
    ' Satisfies rule: Validate parameters
    Throw New ArgumentNullException("clientForm")
    End If

    ' Snap client to the top, left, bottom or right desktop border
    ' as the form is moved near that border.

    Try
    ' Marshal the LPARAM value which is a WINDOWPOS struct
    Dim NewPosition As New WINDOWPOS
    NewPosition = CType(Runtime.InteropServices.Marshal.PtrToStructu re( _
    LParam, GetType(WINDOWPOS)), WINDOWPOS)

    If NewPosition.y = 0 OrElse NewPosition.x = 0 Then
    Return ' Nothing to do!
    End If

    ' Adjust the client size for borders and caption bar
    Dim ClientRect As Rectangle = clientForm.RectangleToScreen(clientForm.ClientRect angle)
    ClientRect.Width += SystemInformation.FrameBorderSize.Width - widthAdjustment
    ClientRect.Height += (SystemInformation.FrameBorderSize.Height + SystemInformation.CaptionHeight)

    ' Now get the screen working area (without taskbar)
    Dim WorkingRect As Rectangle = Screen.GetWorkingArea(clientForm.ClientRectangle)

    ' Left border
    If NewPosition.x >= WorkingRect.X - mSnapOffset AndAlso _
    NewPosition.x <= WorkingRect.X + mSnapOffset Then
    NewPosition.x = WorkingRect.X
    End If

    ' Get screen bounds and taskbar height (when taskbar is horizontal)
    Dim ScreenRect As Rectangle = Screen.GetBounds(Screen.PrimaryScreen.Bounds)
    Dim TaskbarHeight As Integer = ScreenRect.Height - WorkingRect.Height

    ' Top border (check if taskbar is on top or bottom via WorkingRect.Y)
    If NewPosition.y >= -mSnapOffset AndAlso _
    (WorkingRect.Y > 0 AndAlso NewPosition.y <= (TaskbarHeight + mSnapOffset)) OrElse _
    (WorkingRect.Y <= 0 AndAlso NewPosition.y <= (mSnapOffset)) Then
    If TaskbarHeight > 0 Then
    NewPosition.y = WorkingRect.Y ' Horizontal Taskbar
    Else
    NewPosition.y = 0 ' Vertical Taskbar
    End If
    End If

    ' Right border
    If NewPosition.x + ClientRect.Width <= WorkingRect.Right + mSnapOffset AndAlso _
    NewPosition.x + ClientRect.Width >= WorkingRect.Right - mSnapOffset Then
    NewPosition.x = WorkingRect.Right - (ClientRect.Width + SystemInformation.FrameBorderSize.Width)
    End If

    ' Bottom border
    If NewPosition.y + ClientRect.Height <= WorkingRect.Bottom + mSnapOffset AndAlso _
    NewPosition.y + ClientRect.Height >= WorkingRect.Bottom - mSnapOffset Then
    NewPosition.y = WorkingRect.Bottom - (ClientRect.Height + SystemInformation.FrameBorderSize.Height)
    End If

    ' Marshal it back
    Runtime.InteropServices.Marshal.StructureToPtr(New Position, LParam, True)
    Catch ex As ArgumentException
    End Try
    End Sub[/highlight]

    You're done
    Last edited by Jason; 02-15-2011 at 09:23 PM.

  18. The Following 4 Users Say Thank You to Hassan For This Useful Post:

    Blubb1337 (06-11-2010),Lolland (06-11-2010),Ninja® (09-12-2011),Tony Stark` (02-17-2011)

  19. #10
    MJLover's Avatar
    Join Date
    Feb 2010
    Gender
    male
    Location
    Neverland
    Posts
    759
    Reputation
    33
    Thanks
    110
    My Mood
    Cheerful
    It's a piece of snippet ppl2pass requested me. I was unable to deliver him on MSN coz of internet issues:


    Code:
    Function StringToHex(ByVal text As String) As String
            Dim hex As String = Nothing
            For i As Integer = 0 To text.Length - 1
                hex &= Asc(text.Substring(i, 1)).ToString("x").ToUpper
            Next
            Return hex
        End Function
    Use this function to convert each value to hex:

    Code:
    Sub conversion(ByVal s As String)
            Dim n As String = s
            Dim x As Boolean = False
            Dim y As Boolean = False
            Dim str As String = ""
            For i As Integer = 1 To n.Length
                Dim c As String = Mid(n, i, 1)
                If c = "[" Then
                    x = True
                End If
                If c = "]" Then
                    If x Then
                        x = False
                        y = True
                        str += "]" & vbCrLf
                    End If
                End If
                If x Then
                    str += c
                End If
            Next
            Dim g() As String = str.Split(ChrW(10))
            If g.Length < 1 Then
                Exit Sub
            End If
            For Each q As String In g
                If Not q = vbNullString Then
    q=q.replace("[","")
    q=q.replace("]","")
                    MsgBox(StringToHex(q))
                End If
            Next
        End Sub
    Last edited by MJLover; 06-27-2010 at 12:06 AM.

  20. The Following 3 Users Say Thank You to MJLover For This Useful Post:

    Lolland (06-26-2010),Ninja® (09-12-2011),Tony Stark` (02-17-2011)

  21. #11
    Blubb1337's Avatar
    Join Date
    Sep 2009
    Gender
    male
    Location
    Germany
    Posts
    5,915
    Reputation
    161
    Thanks
    3,108
    Calculating the md5 checksum of a file(used it for my md5 updater):

    Code:
    Public Function MD5File(ByVal filepath As String) As String
    
            ' open file (as read-only)
            Using reader As New System.IO.FileStream(filepath, IO.FileMode.Open, IO.FileAccess.Read)
                Using md5 As New System.Security.Cryptography.MD5CryptoServiceProvider
    
                    ' hash contents of this stream
                    Dim hash() As Byte = MD5.ComputeHash(reader)
    
                    ' return formatted hash
                    Return ByteArrayToString(hash)
    
                End Using
            End Using
    
        End Function
    
        ' utility function to convert a byte array into a hex string
        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().ToLower
    
        End Function
    Code:
    dim s as string = md5file("C:\nub.txt")



  22. The Following User Says Thank You to Blubb1337 For This Useful Post:

    Ninja® (09-12-2011)

  23. #12
    Blubb1337's Avatar
    Join Date
    Sep 2009
    Gender
    male
    Location
    Germany
    Posts
    5,915
    Reputation
    161
    Thanks
    3,108
    Move from with noborderstyle BY DRAGGING

    Code:
    #Region " ClientAreaMove Handling "
    Const WM_NCHITTEST As Integer = &H84
    Const HTCLIENT As Integer = &H1
    Const HTCAPTION As Integer = &H2
    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    Select Case m.Msg
    Case WM_NCHITTEST
    MyBase.WndProc(m)
    If m.Result = HTCLIENT Then m.Result = HTCAPTION
    'If m.Result.ToInt32 = HTCLIENT Then m.Result = IntPtr.op_Explicit(HTCAPTION) 'Try this in VS.NET 2002/2003 if the latter line of code doesn't do it... thx to Suhas for the tip.
    Case Else
    'Make sure you pass unhandled messages back to the default message handler.
    MyBase.WndProc(m)
    End Select
    End Sub
    #End Region



  24. The Following 5 Users Say Thank You to Blubb1337 For This Useful Post:

    /b/oss (06-30-2010),DawgiiStylz (02-05-2013),Jason (06-27-2011),Ninja® (09-12-2011),willrulz188 (07-24-2011)

  25. #13
    DawgiiStylz's Avatar
    Join Date
    Aug 2009
    Gender
    male
    Location
    Dawg House
    Posts
    7,811
    Reputation
    219
    Thanks
    2,896
    My Mood
    Tired

    Convert BBCode to HTML code

    Code:
    Public Function BBCode(ByVal strTextToReplace As String) As String
    
    
            '//Define regex
            Dim regExp As Regex
    
    
            '//Regex for URL tag without anchor
            regExp = New Regex("\[url\]([^\]]+)\[\/url\]")
            strTextToReplace = regExp.Replace(strTextToReplace, "<a href=""$1"">$1</a>")
    
    
            '//Regex for URL with anchor
            regExp = New Regex("\[url=([^\]]+)\]([^\]]+)\[\/url\]")
            strTextToReplace = regExp.Replace(strTextToReplace, "<a href=""$1"">$2</a>")
    
    
            '//Image regex
            regExp = New Regex("\[img\]([^\]]+)\[\/img\]")
            strTextToReplace = regExp.Replace(strTextToReplace, "<img src=""$1"" />")
    
    
            '//Bold text
            regExp = New Regex("\[b\](.+?)\[\/b\]")
            strTextToReplace = regExp.Replace(strTextToReplace, "<b>$1</b>")
    
    
            '//Italic text
            regExp = New Regex("\[i\](.+?)\[\/i\]")
            strTextToReplace = regExp.Replace(strTextToReplace, "<i>$1</i>")
    
    
            '//Underline text
            regExp = New Regex("\[u\](.+?)\[\/u\]")
            strTextToReplace = regExp.Replace(strTextToReplace, "<u>$1</u>")
    
    
            '//Font size
            regExp = New Regex("\[size=([^\]]+)\]([^\]]+)\[\/size\]")
            strTextToReplace = regExp.Replace(strTextToReplace, "<span style=""font-size: $1"">$2</span>")
    
    
            '//Font color
            regExp = New Regex("\[color=([^\]]+)\]([^\]]+)\[\/color\]")
            strTextToReplace = regExp.Replace(strTextToReplace, "<span style=""color: $1"">$2</span>")
    
    
            Return strTextToReplace
        End Function
    Credits to owner

  26. #14
    zJester's Avatar
    Join Date
    Dec 2013
    Gender
    male
    Posts
    1
    Reputation
    10
    Thanks
    0
    Just wanted to say that this is an excellent resource. -thanks-

  27. #15
    MPGBat's Avatar
    Join Date
    Oct 2018
    Gender
    female
    Posts
    17
    Reputation
    10
    Thanks
    5
    My Mood
    Amused

    Bookmarking

    Bookmarking this page these are very helpful.
    Was just about to make a program n found a snippet on here that would help

Page 1 of 8 123 ... LastLast