How do I convert a two-dim array to a one-dim? - vb.net

the problem is that I first have to convert the two-dim to a one-dim, then find the selected index and then convert again and then save the new index. after that I have to use the right string.format to show the right output.. I'm just confused =(
In the program there are two text boxes that ask for "row" and "col" size and then you press the button and a list box shows
...............................................................................................................................
Row...Col.......................................................................................................................................
1------1----Vacant ........................................................................
1......2.......Vacant...................................................................................................
1......3.......Vacant....................................................................................................................................
2------1----Vacant.........................................................................................................................
2......2.......Vacant....................................................................................................................................
2......3.......Vacant..........................................................................................................................................................
3------1----Vacant....................................................................................................................................
etc.............................................................................................................................................................
and when I double click one line it has to say "Reserved"
Can someone help me what to do this please?
This is my project folder so far here you can see my failed code and this is my assignment
This is how the program is supposed to look like in the end
'Created by: Hans Elias Juneby
'Started: July 10, 2010 Completed July 0, 2010
Public Class MainFrame
'''<summary>
''' Enum used for choices of showing results
''' </summary>
'''<remarks></remarks>
Private Enum UpdateOptions
ShowAllSeats 'reserved and vacant seats
ShowOnlyVacantSeats 'Only vacant seats
ShowOnlyReservedSeats 'Only reserved seats
End Enum
'Instance variables
Private bookingObj As SeatBooking = New SeatBooking()
Private showOptions As UpdateOptions = UpdateOptions.ShowAllSeats
'''<summary>
''' Default constructor
''' Initialize components and do other preparations.
''' This method is called automatically before the form is made visible
''' </summary>
''' <remarks></remarks>
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' My initialization
InitializeControlvalues()
UpdateResults()
End Sub
'''<summary>
''' Organize initiations
''' Fill comboboxes with options (strings), set default values, etc
''' </summary>
'''<remarks></remarks>
Private Sub InitializeControlvalues()
FillUnitTypeList()
lstUnits.SelectedIndex = -1
cmbShowOptions.Items.AddRange([Enum].GetNames(GetType(UpdateOptions)))
cmbShowOptions.SelectedIndex = 0
rbtnLetters.Checked = True
' txtNumOfSeats.Text = bookingObj.GetMaxCols.ToString() 'default values
' txtNumOfRows.Text = bookingObj.GetMaxRows.ToString() 'default values
lblNumVacants.Text = String.Empty 'default values
lblTotal.Text = String.Empty 'default values
lblPercent.Text = String.Empty 'default values
End Sub
''' <summary>
''' Clear listbox, format new strings with the help of the bookingObj and
'''fill in the box.
''' </summary>
''' <remarks></remarks>
Private Sub UpdateResults()
End Sub
'''<summary>
''' Helper function that returns a string containing a string "** Reserved **" or
'''"Vacant" or no text according the value in showOptions. THe UpdateResults
''' calls this function in detecting which string to show in the listbox
''' </summary>
''' <param name="row">Input</param>
''' <param name="col">Input</param>
''' <returns>A formatted string as explained above</returns>
'''<remarks></remarks>
Private Function GetReservationStatusString()
Select Case (cmbShowOptions.SelectedIndex)
Case 0
Case 1
Case 2
End Select
End Function
'Fills values in the combobox
Private Sub FillUnitTypeList()
Dim units As String() = {"Bus Seats", "Train Seats", "Plane Seats"}
cmbUnitType.Items.AddRange(units)
cmbUnitType.SelectedIndex = 0
End Sub
Private Sub cmbShowOptions_SelectedIndexChange(ByVal sender As System.Object, ByVal e As System.GC)
showOptions = DirectCast(cmbShowOptions.SelectedIndex, UpdateOptions)
UpdateResults()
End Sub
Private Sub btnMatrix_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMatrix.Click
Dim SeatBooking As New SeatBooking
bookingObj.GetMaxRows.ToString()
bookingObj.GetMaxCols.ToString()
lblTotal.Text = txtNumOfRows.Text * txtNumOfSeats.Text
End Sub
''' <summary>
''' Event-handler for the double-click event.
''' Reserve/cancel the seat chosen in the listbox (call bookingObj.SetRowAndCOlumnValue),
''' only if the showOption is Show ALL; otherwise, give an error message and do nothing.
''' </summary>
''' <param name="sender">sender-object from the caller</param>
''' <param name="e">EventArgs object from the caller</param>
''' <remarks></remarks>
Private Sub lstUnits_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstUnits.DoubleClick
lblNumVacants.Text = lblTotal.Text - 1
Return
End Sub
''' <summary>
''' Event-handler method for change in the radiobutton
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub rbtnLetters_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbtnLetters.CheckedChanged
UpdateResults()
Dim A As Integer = 65
Dim myChar As Char
Dim col As Integer = 0
myChar = Convert.ToChar((A + col))
End Sub
Private Sub UpdateUnit()
'Dim strText As String = bookingObj.GetUnitName(cmbUnitType.SelectedIndex)
' lblVacantUnits.Text
End Sub
End Class
then the SeatBook class:
'Created by: Hans Elias Juneby
'Started: July 10, 2010 Completed July 0, 2010
Public Class SeatBooking
Private array As Double() 'Declaration of the array
Private lastIndex As Integer = 0 'last filled position (lastIndex+1 = number of items
'''<summary>
''' Create (or recreate) the matrix with the given size
''' </summary>
'''<param name="rowSize">Number of rows</param>
''' <param name="colSize">Number of columns</param>
'''<remarks></remarks>
Public Sub CreateArray(ByVal rowSize As Integer, ByVal colSize As Integer)
Debug.Assert(rowSize >= 0) 'Program execution halts here in case size is <0;
array = New Double(rowSize - 1) {}
Debug.Assert(colSize >= 0) 'Program execution halts here in case size is <0;
array = New Double(colSize - 1) {}
Dim seatMatrix As Boolean(,)
seatMatrix = New Boolean(rowSize, colSize) {}
End Sub
'''<summary>
''' Calculate the total number of elements(row*col)
''' </summary>
'''<returns>The total number of elements</returns>
'''<remarks></remarks>
Public Function GetMaxCount() As Integer
End Function
'''<summary>
''' Check if a seat in a specific row and column is reserved.
''' </summary>
'''<param name="row">given row</param>
'''<param name="col">given col</param>
'''<returns>True if the seat is reserved and false otherwise</returns>
'''<remarks></remarks>
Public Function IsReserved(ByVal row As Integer, ByVal col As Integer)
End Function
'''<summary>
''' Make a new reservation or cancel an existing. This process is onde by
''' reversing the boolean value in the given position in the matrix, from true to
''' false (reverse the seat) or vice versa(Cancel the reservation)
''' </summary>
'''<param name="row">given row</param>
'''<param name="col">given col</param>
'''<remarks></remarks>
Public Sub Reserve(ByVal row As Integer, ByVal col As Integer)
End Sub
'''<summary>
''' Thenumber of rows in the Matrix
''' </summary>
''' <returns>The number of rows</returns>
''' <remarks></remarks>
Public Function GetMaxRows() As Integer
Dim colsize As Integer = MainFrame.txtNumOfSeats.Text
Dim rowsize As Integer = MainFrame.txtNumOfRows.Text
CreateArray(colsize, rowsize)
For i As Integer = 0 To array.Length - 1
MainFrame.lstUnits.Items.Add("----" & i & "---" & GetMaxCols.ToString.Length)
Next
End Function
'''<summary>
''' Thenumber of columns in the Matrix
''' </summary>
''' <returns>The number of columns</returns>
''' <remarks></remarks>
Public Function GetMaxCols() As Integer
Dim colsize As Integer = MainFrame.txtNumOfSeats.Text
Dim rowsize As Integer = MainFrame.txtNumOfRows.Text
CreateArray(rowsize, colsize)
For h As Integer = 0 To array.Length - 1
Next
End Function
'''<summary>
''' The method first finds the first vacant pos in the matrix (row, col)
''' and then calls another method MatrixIndexToVectorialIndex that determines which
''' position the element has if the matrix was rolled out into a one-dimensional
''' array. In a 3x3 matrix, the element in position (1,1) has an index 4 in
''' one-dimensional array. The method is useful when updating the listbox in the
''' GUI which contains a one-dimensional array of strings. The method determines which
''' position (row,col) in the matrix corresponds to an item (row) in the listbox.
''' </summary>
'''<returns>The index, considering the matrix as one long vector, to the first vacant
''' position ( the first False value). A value -1 is returned if no vacant element is
''' found</returns>
'''<remarks></remarks>
Public Function GetFirstVacantPosition() As Integer
End Function
''' <summary>
''' Determine a corresponding index for an element at (row,col) in a one-dimensional
''' presentation of the matrix. Think of the matrix as beeing rolled out into a one-dim
''' array. In a 3x3 matrix, the element in position (1,1) has an index 4 in
''' one-dimensional array.
''' 20 11 22
''' 33 41 55
''' 60 7 99 Consider value (1,1)=41
''' The above matrix can now be represented as one dimensional array. This makes it
''' easier to update the listbox in the GUI.
''' 20 11 22 33 41 55 60 7 99 value(4)=41
''' Index 0 1 2 3 4 5 6 7 8
'''Hence, index (1,1) in the matrix corresponds to row 4 in the listbox (one-dim array)
''' </summary>
''' <param name="row"></param>
''' <param name="col"></param>
''' <returns>The new index as explained above</returns>
''' <remarks></remarks>
Public Function MatrixIndexToVectorIndex(ByVal row As Integer, ByVal col As Integer)
End Function
''' <summary>
''' Determines the index in the matrix (row,col) that corresponds to a given
''' index in a one-dim array (listbox). This method actually is reverse process of
''' the method MatrixIndexToVectorIndex (see above). The parameter row contains
''' the input, i.e. index of the element in a one-dim array. The results (row and col)
''' are saved and sent back to the caller via the ref variables row,col.
''' </summary>
''' <param name="row">Input and output parameter</param>
''' <param name="col">Output parameter</param>
''' <remarks></remarks>
Public Sub VectorIndexToMatrixIndex(ByRef row As Integer, ByRef col As Integer)
End Sub
''' <summary>
''' This function receives an index in a one-dim array (e.g. listbox) and calls
''' the method VectorIndexToMatrixIndex to fin the same position in the matrix.
''' It then calls the function Reserve to either reserve or cancel a booking.
''' (If False value is saved in the element, it reserves the seat by changing
''' the value to True, and vice-versa).
''' </summary>
''' <param name="oneDimListIndex"></param>
''' <remarks></remarks>
Public Sub SetRowAndColumnValue(ByVal oneDimListIndex As Integer)
End Sub
''' <summary>
''' Calculate the total number of the reserved seats, i.e. the total
''' number of the True values in the matrix.
''' </summary>
''' <returns>Number of reserved seats</returns>
''' <remarks></remarks>
Public Function GetNumOfReservedSeats() As Integer
End Function
''' <summary>
''' Calculate the total number of the vacant seats, i.e the total
''' number of the False values in the matrix.
''' </summary>
''' <returns>number of vacant seats</returns>
''' <remarks></remarks>
Public Function GetNumOfVacantSeats() As Integer
End Function
''' <summary>
''' Relation between the reserved seats and the total number of seats in percent.
''' </summary>
''' <returns>Percent of Reservation</returns>
''' <remarks></remarks>
Public Function PercentOfReservation() As Double
End Function
End Class

Personally I would rather use a hash table for this task [personal preference for speed] but as you need to either use a two-dimensional array or matrix according to your project specs it may be easier to accomplish this by using a 2-dimensional array of type Boolean
Dim ReservationArray(NumRows - 1, NumColumns - 1) as Boolean
These values will default to false indicating that seat is vacant and to reserve the seat all you do is change this value to true
I've done basically the same project a while back for a course I was studying at the time you're welcome to look through the coding and modify it as suits your needs
You can download my project from the link below (Visual Studio 2008 Project)
A big difference between our projects is the use of a datagridview instead of a listbox :) have a look at how this simplifies your task
Reservation_Project.zip

Related

Change the colour of some letters in a particular column in datagridview

I have a datagridview and a textbox. I want to do something like this.
If (textboxsearch.text.contains) any letter/character in (datagridview1. Columns (6).value.tostring) Then the colour of that particular latter/character in datagridview1. Columns (6) will turn into green.
I searched in internet but I failed. Help please. I am using vb.net 2019. Thanks.
I didn't expect you to get the whole way yourself but I did hope to see you put some effort into coming up with your own solution. I did some testing myself, using the link I provided in the comments as a starting point, and I came up with something that works. It's relatively complex so I figured that I'd just provide it as is, rather than waiting around to see how far you can get on your own.
Firstly, here's a useful type:
''' <summary>
''' Represents a section of a <see cref="String"/> that can be highlighted.
''' </summary>
Public Structure HighlightableSubstring
''' <summary>
''' The index at which the substring starts.
''' </summary>
''' <returns>
''' An <see cref="Int32"/> that represents the start index of the substring.
''' </returns>
Public ReadOnly Property StartIndex As Integer
''' <summary>
''' The number of characters in the substring.
''' </summary>
''' <returns>
''' An <see cref="Int32"/> that represents the length of the substring.
''' </returns>
Public ReadOnly Property Length As Integer
''' <summary>
''' Indicates whether or not the substring is highlighted.
''' </summary>
''' <returns>
''' <b>True</b> if the substring is highlighted; otherwise, <b>False</b>.
''' </returns>
Public ReadOnly Property IsHighlighted As Boolean
''' <summary>
''' Creates a new instance of the <see cref="HighlightableSubstring"/> class.
''' </summary>
''' <param name="startIndex">
''' The index at which the substring starts.
''' </param>
''' <param name="length">
''' The number of characters in the substring.
''' </param>
''' <param name="isHighlighted">
''' Indicates whether or not the substring is highlighted.
''' </param>
Public Sub New(startIndex As Integer, length As Integer, isHighlighted As Boolean)
Me.StartIndex = startIndex
Me.Length = length
Me.IsHighlighted = isHighlighted
End Sub
End Structure
Here's the method that makes use of that type and does the drawing:
''' <summary>
''' Draws text with instances of a specific substring highlighted.
''' </summary>
''' <param name="g">
''' The object with which to draw the text.
''' </param>
''' <param name="text">
''' The text to draw.
''' </param>
''' <param name="highlightText">
''' The substring to highlight in the drawn text.
''' </param>
''' <param name="defaultColour">
''' The default colour in which to draw the text.
''' </param>
''' <param name="highlightColour">
''' The colour in which to draw the highlighted sections of the text.
''' </param>
''' <param name="font">
''' The font in which to draw the text.
''' </param>
''' <param name="location">
''' The location of the top-left corner of the bounds within which to draw the text.
''' </param>
Private Sub DrawTextWithHighlights(g As Graphics,
text As String,
highlightText As String,
defaultColour As Color,
highlightColour As Color,
font As Font,
location As PointF)
If String.IsNullOrWhiteSpace(text) Then
Return
End If
Dim textLength = text.Length
Dim highlightTextLength = highlightText.Length
'The sections of the text that are highlighted and not highlighted.
Dim sections As New List(Of HighlightableSubstring)
'The index at which to start searching for the highlight text.
Dim startIndex = 0
If Not String.IsNullOrWhiteSpace(highlightText) Then
'Find the first instance of the highlight text.
Dim highlightIndex = text.IndexOf(highlightText)
'Keep searching until no more instances of the highlight text can be found.
Do Until highlightIndex = -1
'Check whether there is text before the found instance of the highlight text.
If highlightIndex > startIndex Then
'Add a section for the non-highlighted text.
sections.Add(New HighlightableSubstring(startIndex, highlightIndex - startIndex, False))
End If
'Add a section for the highlighted text.
sections.Add(New HighlightableSubstring(highlightIndex, highlightTextLength, True))
'Find the next instance of the highlight text.
startIndex = highlightIndex + highlightTextLength
highlightIndex = text.IndexOf(highlightText, startIndex)
Loop
End If
'Check whether there is text after the last instance of the highlight text.
If startIndex < textLength Then
'Add a section for the non-highlighted text.
sections.Add(New HighlightableSubstring(startIndex, textLength - startIndex, False))
End If
Dim format As New StringFormat
'Set a range for each section of the text.
format.SetMeasurableCharacterRanges(sections.Select(Function(hs) New CharacterRange(hs.StartIndex, hs.Length)).ToArray())
'Get the box that the text would normally occupy.
Dim layoutRect As New RectangleF(location, g.MeasureString(text, font))
'Get the regions occupied by the sections of the text.
Dim regions = g.MeasureCharacterRanges(text, font, layoutRect, format)
'Create brushes for the specified colours.
Using defaultBrush As New SolidBrush(defaultColour),
highlightBrush As New SolidBrush(highlightColour)
For i = 0 To regions.GetUpperBound(0)
'Get the current section.
Dim section = sections(i)
'Get the bounds for the current section.
Dim bounds = regions(i).GetBounds(g)
'Draw the current section of the text using the appropriate colour.
g.DrawString(text.Substring(section.StartIndex, section.Length),
font,
If(section.IsHighlighted,
highlightBrush,
defaultBrush),
bounds.X,
bounds.Y)
Next
End Using
End Sub
Here's how I initially tested that code, without a DataGridView:
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
e.Graphics.DrawString("highlight", Font, Brushes.Black, 100, 50)
DrawTextWithHighlights(e.Graphics, "highlight", "ig", Color.Black, Color.Red, Font, New PointF(100, 70))
e.Graphics.DrawString("abcdababefab", Font, Brushes.Black, 100, 150)
DrawTextWithHighlights(e.Graphics, "abcdababefab", "ab", Color.Black, Color.Red, Font, New PointF(100, 170))
End Sub
I used the second text to test how the code behaved when the highlight text was found at the beginning and end of the text and when two instances were found together and it worked as expected. If you run that code then you'll see that there's a slight offset between the horizontal position of the text drawn with a single call to DrawString and that containing the highlighting. I don't think that it's enough to be a problem but you can address it if you want to.
To use that method with a DataGridView, I did this:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
DataGridView1.Refresh()
End Sub
Private Sub DataGridView1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 Then
'Draw all the required parts of the cell except the text.
e.Paint(e.ClipBounds, e.PaintParts And Not DataGridViewPaintParts.ContentForeground)
'Draw the text.
DrawTextWithHighlights(e.Graphics,
e.FormattedValue?.ToString(),
TextBox1.Text,
DataGridView1.ForeColor,
Color.Red,
DataGridView1.Font,
e.CellBounds.Location)
e.Handled = True
End If
End Sub
In my testing, that worked to properly highlight the text when making changes in the grid or in the TextBox. The one issue with that is where the text gets drawn in the cell. I'll leave it to you to figure out that detail.

How to use extender provider in vb.net

I have this code I want to use it in my form
how to do it?
Imports System.ComponentModel
'...
<ProvideProperty("NullableTextBox", typeof(TextBox) Is )>
Partial Public Class NullableTextBox
Inherits Component
Implements IExtenderProvider
Dim _nullables As Dictionary(Of Control, Boolean) = New Dictionary(Of Control, Boolean)
''' <summary>
''' This is the get part of the extender property.
''' It is actually a method because it takes the control.
''' </summary>
''' <param name="control"></param>
<DefaultValue(False), _
Category("Data")> _
Public Function GetNullableBinding(ByVal control As Control) As Boolean
Dim nullableBinding As Boolean = False
_nullables.TryGetValue(control, nullableBinding)
Return nullableBinding
End Function
''' <summary>
''' This is the set part of the extender property.
''' It is actually a method because it takes the control.
''' </summary>
''' <param name="control"></param>
''' <param name="nullable"></param>
Public Sub SetNullableBinding(ByVal control As Control, ByVal nullable As Boolean)
If _nullables.ContainsKey(control) Then
_nullables(control) = nullable
Else
_nullables.Add(control, nullable)
End If
If nullable Then
' Add a parse event handler.
AddHandler control.DataBindings("Text").Parse, AddressOf Me.NullableExtender_Parse
End If
End Sub
''' <summary>
''' When parsing, set the value to null if the value is empty.
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
Private Sub NullableExtender_Parse(ByVal sender As Object, ByVal e As ConvertEventArgs)
If (e.Value.ToString.Length = 0) Then
e.Value = Nothing
End If
End Sub
End Class

How to create non-repeating random numbers in VB

I'm creating a simple game in VB, as the player takes a shot, the is a random chance it will miss, as multiple shots are taken in each point, i new a new random number when the "Sub playShot()" repeats, the number needs to be between 1 and 10.
This is what i currently have, but it just outputs the same number:
Dim rnd As New Random
Dim shot As Integer = rnd.Next(1, 11)
I'm fine if it repeats the number due to chance, but currently it is always the same.
It just so happens that I have a project open right now that contains extension methods for randomising a list of objects:
Imports System.Runtime.CompilerServices
''' <summary>
''' Contains methods that extend the <see cref="IEnumerable(Of T)"/> interface.
''' </summary>
Public Module EnumerableExtensions
''' <summary>
''' A random number generator.
''' </summary>
Private rng As Random
''' <summary>
''' Randomises the items in an enumerable list.
''' </summary>
''' <typeparam name="T">
''' The type of the items in the list.
''' </typeparam>
''' <param name="source">
''' The input list.
''' </param>
''' <returns>
''' The items from the input list in random order.
''' </returns>
<Extension>
Public Function Randomize(Of T)(source As IEnumerable(Of T)) As IEnumerable(Of T)
EnsureRandomInitialized()
Return source.Randomize(rng)
End Function
''' <summary>
''' Randomises the items in an enumerable list.
''' </summary>
''' <typeparam name="T">
''' The type of the items in the list.
''' </typeparam>
''' <param name="source">
''' The input list.
''' </param>
''' <param name="random">
''' A random number generator.
''' </param>
''' <returns>
''' The items from the input list in random order.
''' </returns>
<Extension>
Public Function Randomize(Of T)(source As IEnumerable(Of T), random As Random) As IEnumerable(Of T)
Return source.OrderBy(Function(o) random.NextDouble())
End Function
''' <summary>
''' Initialises the random number generator if it is not already.
''' </summary>
Private Sub EnsureRandomInitialized()
rng = If(rng, New Random)
End Sub
End Module
With that module in your project, you can do things like this:
Dim numbers = Enumerable.Range(1, 10).Randomize()
For Each number In numbers
Console.WriteLine(number)
Next
That module contains two overloads, with the second allowing you to pass in your own Random instance if desired. If you only ever want to use the first overload then the module can be simplified somewhat:
Imports System.Runtime.CompilerServices
''' <summary>
''' Contains methods that extend the <see cref="IEnumerable(Of T)"/> interface.
''' </summary>
Public Module EnumerableExtensions
''' <summary>
''' A random number generator.
''' </summary>
Private rng As Random
''' <summary>
''' Randomises the items in an enumerable list.
''' </summary>
''' <typeparam name="T">
''' The type of the items in the list.
''' </typeparam>
''' <param name="source">
''' The input list.
''' </param>
''' <returns>
''' The items from the input list in random order.
''' </returns>
<Extension>
Public Function Randomize(Of T)(source As IEnumerable(Of T)) As IEnumerable(Of T)
rng = If(rng, New Random)
Return source.OrderBy(Function(o) rng.NextDouble())
End Function
End Module
When you have a range where you don't want the random values to repeat, the normal solution is to generate all the numbers in the range (in this case 1 through 10) in sequence. Then you shuffle the sequence. Now you can iterate through your shuffled data.

Create a shortcut to a network connection in Windows 7

I am looking for an automatic method to create a shortcut to a network connection in Windows 7. I do not believe this is the same as a shortcut to a file.
I would prefer it to be in vb.net, but anything (VBS, PowerShell, etc...) would be fine.
I came up with the following script, but it requires you to click yes.
Const CSIDL_CONNECTIONS = &H31
Dim objShell As Object = CreateObject("Shell.Application")
Dim objConnectionsFolder = objShell.NameSpace(CSIDL_CONNECTIONS)
For Each objConnection In objConnectionsFolder.Items
If objConnection.name = "Local Area Connection" Then
Dim colVerbs = objConnection.Verbs
For Each objVerb In colVerbs
If Replace(objVerb.name, "&", "") = "Create Shortcut" Then
objVerb.DoIt()
End If
Next
End If
Next
MsgBox("If the script ends too quickly then it doesn't finish.")
Any Suggestions would be greatly appreciated.
Powershell:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("C:\somepath\shortcutName.lnk"));
$Shortcut.TargetPath = "\\server\path";
$Shortcut.Save();
In VB.NET you could try to use my Shortcut Manager Helper Class.
Usage:
Dim Shortcut As New ShortcutManager.ShortcutInfo
With Shortcut
.ShortcutFile = "C:\New shortcut.lnk"
.Target = "\\server\path"
.Description = "Shortcut Description"
.Icon = "Icon.ico"
.IconIndex = 0
End With
ShortcutManager.CreateShortcut(Shortcut)
The Class is partially defined 'cause the character limit of StackOverflow (if you want the full version then go this link):
' ***********************************************************************
' Author : Elektro
' Modified : 02-16-2014
' ***********************************************************************
' <copyright file="ShortcutManager.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Imports "
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.IO
#End Region
#Region " ShortcutManager "
''' <summary>
''' Performs Shortcut related operations.
''' </summary>
Public Class ShortcutManager
#Region " Variables "
Private Shared lnk As New ShellLink()
Private Shared lnk_data As New WIN32_FIND_DATAW()
Private Shared lnk_arguments As New StringBuilder(260)
Private Shared lnk_description As New StringBuilder(260)
Private Shared lnk_target As New StringBuilder(260)
Private Shared lnk_workingdir As New StringBuilder(260)
Private Shared lnk_iconpath As New StringBuilder(260)
Private Shared lnk_iconindex As Integer = -1
Private Shared lnk_hotkey As Short = -1
Private Shared lnk_windowstate As ShortcutWindowState = ShortcutWindowState.Normal
#End Region
#Region " P/Invoke "
<DllImport("shfolder.dll", CharSet:=CharSet.Auto)>
Private Shared Function SHGetFolderPath(
ByVal hwndOwner As IntPtr,
ByVal nFolder As Integer,
ByVal hToken As IntPtr,
ByVal dwFlags As Integer,
ByVal lpszPath As StringBuilder
) As Integer
End Function
<Flags()>
Private Enum SLGP_FLAGS
''' <summary>
''' Retrieves the standard short (8.3 format) file name.
''' </summary>
SLGP_SHORTPATH = &H1
''' <summary>
''' Retrieves the Universal Naming Convention (UNC) path name of the file.
''' </summary>
SLGP_UNCPRIORITY = &H2
''' <summary>
''' Retrieves the raw path name.
''' A raw path is something that might not exist and may include environment variables that need to be expanded.
''' </summary>
SLGP_RAWPATH = &H4
End Enum
<Flags()>
Private Enum SLR_FLAGS
''' <summary>
''' Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
''' the high-order word of fFlags can be set to a time-out value that specifies the
''' maximum amount of time to be spent resolving the link. The function returns if the
''' link cannot be resolved within the time-out duration. If the high-order word is set
''' to zero, the time-out duration will be set to the default value of 3,000 milliseconds
''' (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
''' duration, in milliseconds.
''' </summary>
SLR_NO_UI = &H1
''' <summary>
''' If the link object has changed, update its path and list of identifiers.
''' If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine,
''' whether or not the link object has changed.
''' </summary>
SLR_UPDATE = &H4
''' <summary>
''' Do not update the link information
''' </summary>
SLR_NOUPDATE = &H8
''' <summary>
''' Do not execute the search heuristics
''' </summary>
SLR_NOSEARCH = &H10
''' <summary>
''' Do not use distributed link tracking
''' </summary>
SLR_NOTRACK = &H20
''' <summary>
''' Disable distributed link tracking.
''' By default, distributed link tracking tracks removable media,
''' across multiple devices based on the volume name.
''' It also uses the Universal Naming Convention (UNC) path to track remote file systems,
''' whose drive letter has changed.
''' Setting SLR_NOLINKINFO disables both types of tracking.
''' </summary>
SLR_NOLINKINFO = &H40
''' <summary>
''' Call the Microsoft Windows Installer
''' </summary>
SLR_INVOKE_MSI = &H80
End Enum
''' <summary>
''' Stores information about a shortcut file.
''' </summary>
Public Class ShortcutInfo
''' <summary>
''' Shortcut file full path.
''' </summary>
Public Property ShortcutFile As String
''' <summary>
''' Shortcut Comment/Description.
''' </summary>
Public Property Description As String
''' <summary>
''' Shortcut Target Arguments.
''' </summary>
Public Property Arguments As String
''' <summary>
''' Shortcut Target.
''' </summary>
Public Property Target As String
''' <summary>
''' Shortcut Working Directory.
''' </summary>
Public Property WorkingDir As String
''' <summary>
''' Shortcut Icon Location.
''' </summary>
Public Property Icon As String
''' <summary>
''' Shortcut Icon Index.
''' </summary>
Public Property IconIndex As Integer
''' <summary>
''' Shortcut Hotkey combination.
''' Is represented as Hexadecimal.
''' </summary>
Public Property Hotkey As Short
''' <summary>
''' Shortcut Hotkey modifiers.
''' </summary>
Public Property Hotkey_Modifier As HotkeyModifiers
''' <summary>
''' Shortcut Hotkey Combination.
''' </summary>
Public Property Hotkey_Key As Keys
''' <summary>
''' Shortcut Window State.
''' </summary>
Public Property WindowState As ShortcutWindowState
''' <summary>
''' Indicates if the target is a file.
''' </summary>
Public Property IsFile As Boolean
''' <summary>
''' Indicates if the target is a directory.
''' </summary>
Public Property IsDirectory As Boolean
''' <summary>
''' Shortcut target drive letter.
''' </summary>
Public Property DriveLetter As String
''' <summary>
''' Shortcut target directory name.
''' </summary>
Public Property DirectoryName As String
''' <summary>
''' Shortcut target filename.
''' (File extension is not included in name)
''' </summary>
Public Property FileName As String
''' <summary>
''' Shortcut target file extension.
''' </summary>
Public Property FileExtension As String
End Class
''' <summary>
''' Hotkey modifiers for a shortcut file.
''' </summary>
<Flags()>
Public Enum HotkeyModifiers As Short
''' <summary>
''' The SHIFT key.
''' </summary>
SHIFT = 1
''' <summary>
''' The CTRL key.
''' </summary>
CONTROL = 2
''' <summary>
''' The ALT key.
''' </summary>
ALT = 4
''' <summary>
''' None.
''' Specifies any hotkey modificator.
''' </summary>
NONE = 0
End Enum
''' <summary>
''' The Window States for a shortcut file.
''' </summary>
Public Enum ShortcutWindowState As Integer
''' <summary>
''' Shortcut Window is at normal state.
''' </summary>
Normal = 1
''' <summary>
''' Shortcut Window is Maximized.
''' </summary>
Maximized = 3
''' <summary>
''' Shortcut Window is Minimized.
''' </summary>
Minimized = 7
End Enum
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)>
Private Structure WIN32_FIND_DATAW
Public dwFileAttributes As UInteger
Public ftCreationTime As Long
Public ftLastAccessTime As Long
Public ftLastWriteTime As Long
Public nFileSizeHigh As UInteger
Public nFileSizeLow As UInteger
Public dwReserved0 As UInteger
Public dwReserved1 As UInteger
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)>
Public cFileName As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=14)>
Public cAlternateFileName As String
End Structure
''' <summary>
''' The IShellLink interface allows Shell links to be created, modified, and resolved
''' </summary>
<ComImport(),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("000214F9-0000-0000-C000-000000000046")>
Private Interface IShellLinkW
''' <summary>
''' Retrieves the path and file name of a Shell link object.
''' </summary>
Sub GetPath(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszFile As StringBuilder,
ByVal cchMaxPath As Integer,
ByRef pfd As WIN32_FIND_DATAW,
ByVal fFlags As SLGP_FLAGS)
''' <summary>
''' Retrieves the list of item identifiers for a Shell link object.
''' </summary>
Sub GetIDList(ByRef ppidl As IntPtr)
''' <summary>
''' Sets the pointer to an item identifier list (PIDL) for a Shell link object.
''' </summary>
Sub SetIDList(ByVal pidl As IntPtr)
''' <summary>
''' Retrieves the description string for a Shell link object.
''' </summary>
Sub GetDescription(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszName As StringBuilder,
ByVal cchMaxName As Integer)
''' <summary>
''' Sets the description for a Shell link object.
''' The description can be any application-defined string.
''' </summary>
Sub SetDescription(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszName As String)
''' <summary>
''' Retrieves the name of the working directory for a Shell link object.
''' </summary>
Sub GetWorkingDirectory(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszDir As StringBuilder,
ByVal cchMaxPath As Integer)
''' <summary>
''' Sets the name of the working directory for a Shell link object.
''' </summary>
Sub SetWorkingDirectory(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszDir As String)
''' <summary>
''' Retrieves the command-line arguments associated with a Shell link object.
''' </summary>
Sub GetArguments(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszArgs As StringBuilder,
ByVal cchMaxPath As Integer)
''' <summary>
''' Sets the command-line arguments for a Shell link object.
''' </summary>
Sub SetArguments(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszArgs As String)
''' <summary>
''' Retrieves the hot key for a Shell link object.
''' </summary>
Sub GetHotkey(ByRef pwHotkey As Short)
''' <summary>
''' Sets a hot key for a Shell link object.
''' </summary>
Sub SetHotkey(ByVal wHotkey As Short)
''' <summary>
''' Retrieves the show command for a Shell link object.
''' </summary>
Sub GetShowCmd(ByRef piShowCmd As Integer)
''' <summary>
''' Sets the show command for a Shell link object.
''' The show command sets the initial show state of the window.
''' </summary>
Sub SetShowCmd(ByVal iShowCmd As ShortcutWindowState)
''' <summary>
''' Retrieves the location (path and index) of the icon for a Shell link object.
''' </summary>
Sub GetIconLocation(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszIconPath As StringBuilder,
ByVal cchIconPath As Integer,
ByRef piIcon As Integer)
''' <summary>
''' Sets the location (path and index) of the icon for a Shell link object.
''' </summary>
Sub SetIconLocation(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszIconPath As String,
ByVal iIcon As Integer)
''' <summary>
''' Sets the relative path to the Shell link object.
''' </summary>
Sub SetRelativePath(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszPathRel As String,
ByVal dwReserved As Integer)
''' <summary>
''' Attempts to find the target of a Shell link,
''' even if it has been moved or renamed.
''' </summary>
Sub Resolve(ByVal hwnd As IntPtr,
ByVal fFlags As SLR_FLAGS)
''' <summary>
''' Sets the path and file name of a Shell link object
''' </summary>
Sub SetPath(ByVal pszFile As String)
End Interface
<ComImport(), Guid("0000010c-0000-0000-c000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Private Interface IPersist
<PreserveSig()>
Sub GetClassID(ByRef pClassID As Guid)
End Interface
<ComImport(), Guid("0000010b-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Private Interface IPersistFile
Inherits IPersist
Shadows Sub GetClassID(ByRef pClassID As Guid)
<PreserveSig()>
Function IsDirty() As Integer
<PreserveSig()>
Sub Load(<[In](), MarshalAs(UnmanagedType.LPWStr)>
pszFileName As String,
dwMode As UInteger)
<PreserveSig()>
Sub Save(<[In](), MarshalAs(UnmanagedType.LPWStr)>
pszFileName As String,
<[In](), MarshalAs(UnmanagedType.Bool)>
fRemember As Boolean)
<PreserveSig()>
Sub SaveCompleted(<[In](), MarshalAs(UnmanagedType.LPWStr)>
pszFileName As String)
<PreserveSig()>
Sub GetCurFile(<[In](), MarshalAs(UnmanagedType.LPWStr)>
ppszFileName As String)
End Interface
' "CLSID_ShellLink" from "ShlGuid.h"
<ComImport(),
Guid("00021401-0000-0000-C000-000000000046")>
Private Class ShellLink
End Class
#End Region
#Region " Public Methods "
''' <summary>
''' Creates a shortcut file.
''' </summary>
''' <param name="FilePath">
''' The filepath to create the shortcut.
''' </param>
''' <param name="Target">
''' The target file or directory.
''' </param>
''' <param name="WorkingDirectory">
''' The working directory os the shortcut.
''' </param>
''' <param name="Description">
''' The shortcut description.
''' </param>
''' <param name="Arguments">
''' The target file arguments.
''' This value only should be set when target is an executable file.
''' </param>
''' <param name="Icon">
''' The icon location of the shortcut.
''' </param>
''' <param name="IconIndex">
''' The icon index of the icon file.
''' </param>
''' <param name="HotKey_Modifier">
''' The hotkey modifier(s) which should be used for the hotkey combination.
''' <paramref name="HotkeyModifiers"/> can be one or more modifiers.
''' </param>
''' <param name="HotKey_Key">
''' The key used in combination with the <paramref name="HotkeyModifiers"/> for hotkey combination.
''' </param>
''' <param name="WindowState">
''' The Window state for the target.
''' </param>
Public Shared Sub CreateShortcut(ByVal FilePath As String,
ByVal Target As String,
Optional ByVal WorkingDirectory As String = Nothing,
Optional ByVal Description As String = Nothing,
Optional ByVal Arguments As String = Nothing,
Optional ByVal Icon As String = Nothing,
Optional ByVal IconIndex As Integer = Nothing,
Optional ByVal HotKey_Modifier As HotkeyModifiers = Nothing,
Optional ByVal HotKey_Key As Keys = Nothing,
Optional ByVal WindowState As ShortcutWindowState = ShortcutWindowState.Normal)
' Load Shortcut
LoadShortcut(FilePath)
' Clean objects
Clean()
' Set Shortcut Info
DirectCast(lnk, IShellLinkW).SetPath(Target)
DirectCast(lnk, IShellLinkW).SetWorkingDirectory(If(WorkingDirectory IsNot Nothing,
WorkingDirectory,
Path.GetDirectoryName(Target)))
DirectCast(lnk, IShellLinkW).SetDescription(Description)
DirectCast(lnk, IShellLinkW).SetArguments(Arguments)
DirectCast(lnk, IShellLinkW).SetIconLocation(Icon, IconIndex)
DirectCast(lnk, IShellLinkW).SetHotkey(If(HotKey_Modifier + HotKey_Key <> 0,
Convert.ToInt16(CInt(HotKey_Modifier & Hex(HotKey_Key)), 16),
Nothing))
DirectCast(lnk, IShellLinkW).SetShowCmd(WindowState)
DirectCast(lnk, IPersistFile).Save(FilePath, True)
DirectCast(lnk, IPersistFile).SaveCompleted(FilePath)
End Sub
''' <summary>
''' Creates a shortcut file.
''' </summary>
''' <param name="Shortcut">Indicates a ShortcutInfo object.</param>
Public Shared Sub CreateShortcut(ByVal Shortcut As ShortcutInfo)
CreateShortcut(Shortcut.ShortcutFile,
Shortcut.Target,
Shortcut.WorkingDir,
Shortcut.Description,
Shortcut.Arguments,
Shortcut.Icon,
Shortcut.IconIndex,
Shortcut.Hotkey_Modifier,
Shortcut.Hotkey_Key,
Shortcut.WindowState)
End Sub
#End Region
#Region " Private Methods "
''' <summary>
''' Loads the shortcut object to retrieve information.
''' </summary>
''' <param name="ShortcutFile">
''' The shortcut file to retrieve the info.
''' </param>
Private Shared Sub LoadShortcut(ByVal ShortcutFile As String)
DirectCast(lnk, IPersistFile).Load(ShortcutFile, 0)
End Sub
''' <summary>
''' Clean the shortcut info objects.
''' </summary>
Private Shared Sub Clean()
lnk_description.Clear()
lnk_arguments.Clear()
lnk_target.Clear()
lnk_workingdir.Clear()
lnk_iconpath.Clear()
lnk_hotkey = -1
lnk_iconindex = -1
End Sub
''' <summary>
''' Gets the low order byte of a number.
''' </summary>
Private Shared Function GetLoByte(ByVal Intg As Integer) As Integer
Return Intg And &HFF&
End Function
''' <summary>
''' Gets the high order byte of a number.
''' </summary>
Private Shared Function GetHiByte(ByVal Intg As Integer) As Integer
Return (Intg And &HFF00&) / 256
End Function
#End Region
End Class
#End Region

simulate a keypress using sendmessage

I want simulate a keypress but i have small problem.. What i do with hexadecimal ... its not even working :D Here is where i get that virtual-key hexadecimal: http://msdn.microsoft.com/en-us/library/dd375731%28v=VS.85%29.aspx
Here is my code:
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage2( _
ByVal hwnd As IntPtr, _
ByVal wMsg As Integer, _
ByVal wParam As Integer, _
<MarshalAs(UnmanagedType.LPTStr)> ByVal lParam As String) As Integer
End Function
SendMessage2(WindowHandle, 256, 0x0D, 0)
SendMessage2(WindowHandle, 257, 0x0D, 65539)
Error:
Argument not specified for parameter 'lParam' of 'Private Shared Function SendMessage2(hwnd As System.IntPtr, wMsg As Integer, wParam As Integer, lParam As String) As Integer'.
Comma, ')', or a valid expression continuation expected.
Too many arguments to 'Private Shared Function SendMessage2(hwnd As System.IntPtr, wMsg As Integer, wParam As Integer, lParam As String) As Integer'.
An alternative way to synthesize a keystroke is using the SendInput method, I did an Helper Class to send a Keystroke in a simple way (it needs to be extended for use special chars as string like Ñ or Ç).
Example usages:
AppActivate(Process.GetProcessesByName("notepad").First.Id)
Dim c As Char = Convert.ToChar(Keys.Oemtilde) ' Ñ
Dim Result As Integer = SendInputs.SendKey(Convert.ToChar(c.ToString.ToLower))
MessageBox.Show(String.Format("Successfull events: {0}", CStr(Result)))
SendInputs.SendKey(Keys.Enter)
SendInputs.SendKey(Convert.ToChar(Keys.Back))
SendInputs.SendKeys("Hello World", True)
SendInputs.SendKey(Convert.ToChar(Keys.D0))
SendInputs.SendKeys(Keys.Insert, BlockInput:=True)
SendInputs.MouseClick(SendInputs.MouseButton.RightPress, False)
SendInputs.MouseMove(5, -5)
SendInputs.MousePosition(New Point(100, 500))
Here is the partial Class where I've removed the MouseInput methods, if you want to see the full class then go this link.
' ***********************************************************************
' Author : Elektro
' Modified : 02-21-2014
' ***********************************************************************
' <copyright file="SendInputs.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Imports "
Imports System.Runtime.InteropServices
Imports System.ComponentModel
#End Region
''' <summary>
''' Synthesizes keystrokes, mouse motions, and button clicks.
''' </summary>
Public Class SendInputs
#Region " P/Invoke "
Friend Class NativeMethods
#Region " Methods "
''' <summary>
''' Blocks keyboard and mouse input events from reaching applications.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646290%28v=vs.85%29.aspx
''' </summary>
''' <param name="fBlockIt">
''' The function's purpose.
''' If this parameter is 'TRUE', keyboard and mouse input events are blocked.
''' If this parameter is 'FALSE', keyboard and mouse events are unblocked.
''' </param>
''' <returns>
''' If the function succeeds, the return value is nonzero.
''' If input is already blocked, the return value is zero.
''' </returns>
''' <remarks>
''' Note that only the thread that blocked input can successfully unblock input.
''' </remarks>
<DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall,
SetLastError:=True)>
Friend Shared Function BlockInput(
ByVal fBlockIt As Boolean
) As Integer
End Function
''' <summary>
''' Synthesizes keystrokes, mouse motions, and button clicks.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310%28v=vs.85%29.aspx
''' </summary>
''' <param name="nInputs">
''' Indicates the number of structures in the pInputs array.
''' </param>
''' <param name="pInputs">
''' Indicates an Array of 'INPUT' structures.
''' Each structure represents an event to be inserted into the keyboard or mouse input stream.
''' </param>
''' <param name="cbSize">
''' The size, in bytes, of an 'INPUT' structure.
''' If 'cbSize' is not the size of an 'INPUT' structure, the function fails.
''' </param>
''' <returns>
''' The function returns the number of events that it successfully
''' inserted into the keyboard or mouse input stream.
''' If the function returns zero, the input was already blocked by another thread.
''' </returns>
<DllImport("user32.dll", SetLastError:=True)>
Friend Shared Function SendInput(
ByVal nInputs As Integer,
<MarshalAs(UnmanagedType.LPArray), [In]> ByVal pInputs As INPUT(),
ByVal cbSize As Integer
) As Integer
End Function
#End Region
#Region " Enumerations "
''' <summary>
''' VirtualKey codes.
''' </summary>
Friend Enum VirtualKeys As Short
''' <summary>
''' The Shift key.
''' VK_SHIFT
''' </summary>
SHIFT = &H10S
''' <summary>
''' The DEL key.
''' VK_DELETE
''' </summary>
DELETE = 46S
''' <summary>
''' The ENTER key.
''' VK_RETURN
''' </summary>
[RETURN] = 13S
End Enum
''' <summary>
''' The type of the input event.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
''' </summary>
<Description("Enumeration used for 'type' parameter of 'INPUT' structure")>
Friend Enum InputType As Integer
''' <summary>
''' The event is a keyboard event.
''' Use the ki structure of the union.
''' </summary>
Keyboard = 1
End Enum
''' <summary>
''' Specifies various aspects of a keystroke.
''' This member can be certain combinations of the following values.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
''' </summary>
<Description("Enumeration used for 'dwFlags' parameter of 'KeyboardInput' structure")>
<Flags>
Friend Enum KeyboardInput_Flags As Integer
''' <summary>
''' If specified, the scan code was preceded by a prefix byte that has the value '0xE0' (224).
''' </summary>
ExtendedKey = &H1
''' <summary>
''' If specified, the key is being pressed.
''' </summary>
KeyDown = &H0
''' <summary>
''' If specified, the key is being released.
''' If not specified, the key is being pressed.
''' </summary>
KeyUp = &H2
''' <summary>
''' If specified, 'wScan' identifies the key and 'wVk' is ignored.
''' </summary>
ScanCode = &H8
''' <summary>
''' If specified, the system synthesizes a 'VK_PACKET' keystroke.
''' The 'wVk' parameter must be '0'.
''' This flag can only be combined with the 'KEYEVENTF_KEYUP' flag.
''' </summary>
Unicode = &H4
End Enum
#End Region
#Region " Structures "
''' <summary>
''' Used by 'SendInput' function
''' to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx
''' </summary>
<Description("Structure used for 'INPUT' parameter of 'SendInput' API method")>
<StructLayout(LayoutKind.Explicit)>
Friend Structure Input
' ******
' NOTE
' ******
' Field offset for 32 bit machine: 4
' Field offset for 64 bit machine: 8
''' <summary>
''' The type of the input event.
''' </summary>
<FieldOffset(0)>
Public type As InputType
''' <summary>
''' The information about a simulated mouse event.
''' </summary>
<FieldOffset(8)>
Public mi As MouseInput
''' <summary>
''' The information about a simulated keyboard event.
''' </summary>
<FieldOffset(8)>
Public ki As KeyboardInput
''' <summary>
''' The information about a simulated hardware event.
''' </summary>
<FieldOffset(8)>
Public hi As HardwareInput
End Structure
''' <summary>
''' Contains information about a simulated mouse event.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646273%28v=vs.85%29.aspx
''' </summary>
<Description("Structure used for 'mi' parameter of 'INPUT' structure")>
Friend Structure MouseInput
''' <summary>
''' The absolute position of the mouse,
''' or the amount of motion since the last mouse event was generated,
''' depending on the value of the dwFlags member.
''' Absolute data is specified as the 'x' coordinate of the mouse;
''' relative data is specified as the number of pixels moved.
''' </summary>
Public dx As Integer
''' <summary>
''' The absolute position of the mouse,
''' or the amount of motion since the last mouse event was generated,
''' depending on the value of the dwFlags member.
''' Absolute data is specified as the 'y' coordinate of the mouse;
''' relative data is specified as the number of pixels moved.
''' </summary>
Public dy As Integer
''' <summary>
''' If 'dwFlags' contains 'MOUSEEVENTF_WHEEL',
''' then 'mouseData' specifies the amount of wheel movement.
''' A positive value indicates that the wheel was rotated forward, away from the user;
''' a negative value indicates that the wheel was rotated backward, toward the user.
''' One wheel click is defined as 'WHEEL_DELTA', which is '120'.
'''
''' If 'dwFlags' does not contain 'MOUSEEVENTF_WHEEL', 'MOUSEEVENTF_XDOWN', or 'MOUSEEVENTF_XUP',
''' then mouseData should be '0'.
''' </summary>
Public mouseData As Integer
''' <summary>
''' A set of bit flags that specify various aspects of mouse motion and button clicks.
''' The bits in this member can be any reasonable combination of the following values.
''' The bit flags that specify mouse button status are set to indicate changes in status,
''' not ongoing conditions.
''' For example, if the left mouse button is pressed and held down,
''' 'MOUSEEVENTF_LEFTDOWN' is set when the left button is first pressed,
''' but not for subsequent motions.
''' Similarly, 'MOUSEEVENTF_LEFTUP' is set only when the button is first released.
'''
''' You cannot specify both the 'MOUSEEVENTF_WHEE'L flag
''' and either 'MOUSEEVENTF_XDOWN' or 'MOUSEEVENTF_XUP' flags simultaneously in the 'dwFlags' parameter,
''' because they both require use of the 'mouseData' field.
''' </summary>
Public dwFlags As MouseInput_Flags
''' <summary>
''' The time stamp for the event, in milliseconds.
''' If this parameter is '0', the system will provide its own time stamp.
''' </summary>
Public time As Integer
''' <summary>
''' An additional value associated with the mouse event.
''' An application calls 'GetMessageExtraInfo' to obtain this extra information.
''' </summary>
Public dwExtraInfo As IntPtr
End Structure
''' <summary>
''' Contains information about a simulated keyboard event.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646271%28v=vs.85%29.aspx
''' </summary>
<Description("Structure used for 'ki' parameter of 'INPUT' structure")>
Friend Structure KeyboardInput
''' <summary>
''' A virtual-key code.
''' The code must be a value in the range '1' to '254'.
''' If the 'dwFlags' member specifies 'KEYEVENTF_UNICODE', wVk must be '0'.
''' </summary>
Public wVk As Short
''' <summary>
''' A hardware scan code for the key.
''' If 'dwFlags' specifies 'KEYEVENTF_UNICODE',
''' 'wScan' specifies a Unicode character which is to be sent to the foreground application.
''' </summary>
Public wScan As Short
''' <summary>
''' Specifies various aspects of a keystroke.
''' </summary>
Public dwFlags As KeyboardInput_Flags
''' <summary>
''' The time stamp for the event, in milliseconds.
''' If this parameter is '0', the system will provide its own time stamp.
''' </summary>
Public time As Integer
''' <summary>
''' An additional value associated with the keystroke.
''' Use the 'GetMessageExtraInfo' function to obtain this information.
''' </summary>
Public dwExtraInfo As IntPtr
End Structure
''' <summary>
''' Contains information about a simulated message generated by an input device other than a keyboard or mouse.
''' For more info see here:
''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms646269%28v=vs.85%29.aspx
''' </summary>
<Description("Structure used for 'hi' parameter of 'INPUT' structure")>
Friend Structure HardwareInput
''' <summary>
''' The message generated by the input hardware.
''' </summary>
Public uMsg As Integer
''' <summary>
''' The low-order word of the lParam parameter for uMsg.
''' </summary>
Public wParamL As Short
''' <summary>
''' The high-order word of the lParam parameter for uMsg.
''' </summary>
Public wParamH As Short
End Structure
#End Region
End Class
#End Region
#Region " Enumerations "
#End Region
#Region " Public Methods "
''' <summary>
''' Sends a keystroke.
''' </summary>
''' <param name="key">
''' Indicates the keystroke to simulate.
''' </param>
''' <param name="BlockInput">
''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
''' </param>
''' <returns>
''' The function returns the number of events that it successfully inserted into the keyboard input stream.
''' If the function returns zero, the input was already blocked by another thread.
''' </returns>
Public Shared Function SendKey(ByVal key As Char,
Optional BlockInput As Boolean = False) As Integer
' Block Keyboard and mouse.
If BlockInput Then NativeMethods.BlockInput(True)
' The inputs structures to send.
Dim Inputs As New List(Of NativeMethods.INPUT)
' The current input to add into the Inputs list.
Dim CurrentInput As New NativeMethods.INPUT
' Determines whether a character is an alphabetic letter.
Dim IsAlphabetic As Boolean = Not (key.ToString.ToUpper = key.ToString.ToLower)
' Determines whether a character is an uppercase alphabetic letter.
Dim IsUpperCase As Boolean =
(key.ToString = key.ToString.ToUpper) AndAlso Not (key.ToString.ToUpper = key.ToString.ToLower)
' Determines whether the CapsLock key is pressed down.
Dim CapsLockON As Boolean = My.Computer.Keyboard.CapsLock
' Set the passed key to upper-case.
If IsAlphabetic AndAlso Not IsUpperCase Then
key = Convert.ToChar(key.ToString.ToUpper)
End If
' If character is alphabetic and is UpperCase and CapsLock is pressed down,
' OrElse character is alphabetic and is not UpperCase and CapsLock is not pressed down,
' OrElse character is not alphabetic.
If (IsAlphabetic AndAlso IsUpperCase AndAlso CapsLockON) _
OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso Not CapsLockON) _
OrElse (Not IsAlphabetic) Then
' Hold the character key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = Convert.ToInt16(CChar(key))
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
End With : Inputs.Add(CurrentInput)
' Release the character key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = Convert.ToInt16(CChar(key))
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
End With : Inputs.Add(CurrentInput)
' If character is alphabetic and is UpperCase and CapsLock is not pressed down,
' OrElse character is alphabetic and is not UpperCase and CapsLock is pressed down.
ElseIf (IsAlphabetic AndAlso IsUpperCase AndAlso Not CapsLockON) _
OrElse (IsAlphabetic AndAlso Not IsUpperCase AndAlso CapsLockON) Then
' Hold the Shift key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = NativeMethods.VirtualKeys.SHIFT
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
End With : Inputs.Add(CurrentInput)
' Hold the character key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = Convert.ToInt16(CChar(key))
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyDown
End With : Inputs.Add(CurrentInput)
' Release the character key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = Convert.ToInt16(CChar(key))
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
End With : Inputs.Add(CurrentInput)
' Release the Shift key.
With CurrentInput
.type = NativeMethods.InputType.Keyboard
.ki.wVk = NativeMethods.VirtualKeys.SHIFT
.ki.dwFlags = NativeMethods.KeyboardInput_Flags.KeyUp
End With : Inputs.Add(CurrentInput)
End If ' UpperCase And My.Computer.Keyboard.CapsLock is...
' Send the input key.
Return NativeMethods.SendInput(Inputs.Count, Inputs.ToArray,
Marshal.SizeOf(GetType(NativeMethods.Input)))
' Unblock Keyboard and mouse.
If BlockInput Then NativeMethods.BlockInput(False)
End Function
''' <summary>
''' Sends a keystroke.
''' </summary>
''' <param name="key">
''' Indicates the keystroke to simulate.
''' </param>
''' <param name="BlockInput">
''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
''' </param>
''' <returns>
''' The function returns the number of events that it successfully inserted into the keyboard input stream.
''' If the function returns zero, the input was already blocked by another thread.
''' </returns>
Public Shared Function SendKey(ByVal key As Keys,
Optional BlockInput As Boolean = False) As Integer
Return SendKey(Convert.ToChar(key), BlockInput)
End Function
''' <summary>
''' Sends a string.
''' </summary>
''' <param name="String">
''' Indicates the string to send.
''' </param>
''' <param name="BlockInput">
''' If set to <c>true</c>, the keyboard and mouse are blocked until the keystroke is sent.
''' </param>
''' <returns>
''' The function returns the number of events that it successfully inserted into the keyboard input stream.
''' If the function returns zero, the input was already blocked by another thread.
''' </returns>
Public Shared Function SendKeys(ByVal [String] As String,
Optional BlockInput As Boolean = False) As Integer
Dim SuccessCount As Integer = 0
' Block Keyboard and mouse.
If BlockInput Then NativeMethods.BlockInput(True)
For Each c As Char In [String]
SuccessCount += SendKey(c, BlockInput:=False)
Next c
' Unblock Keyboard and mouse.
If BlockInput Then NativeMethods.BlockInput(False)
Return SuccessCount
End Function
#End Region
End Class
Because you are passing in a hexadecimal, in VB.NET every hexadecimal starts with &H followed by everything after the 0x
So your SendMessage2(WindowHandle, 256, 0x0D, 0) needs to be SendMessage2(WindowHandle, 256, &H0D, 0)
The hexadecimal is the key you want to send. By changing that you change the key you are sending to the window.