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.
Related
I am able to retrieve it from a COM object via Reflection and run it with the MethodInfo.Invoke method.
However, I am trying to create a Delegate to be faster because I will use it in a loop. Unfortunately, I couldn't find a solution to the error message below. How can I create a delegate for a COM method?
"Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type."
My Delegate:
Public Delegate Function GetDriveNameDelegate(path As String) As String
My test Button:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fsoType As Type = Type.GetTypeFromProgID("Scripting.FileSystemObject")
Dim fsoInstance As Object = Activator.CreateInstance(fsoType)
'Dim result As Type
#Region " This is working... "
'Dim dispatch As IDispatchInfo = fsoInstance
'dispatch.GetTypeInfo(0, 0, result)
'Dim mi As MethodInfo = result.GetMethod("GetDriveName")
'Dim param = New Object() {"C:\Windows"}
'MessageBox.Show(mi.Invoke(fsoInstance, param))
#End Region
#Region " This is not working... "
Dim fsoDelegate As GetDriveNameDelegate = GetDelegateFromCOM(fsoInstance, "GetDriveName")
MessageBox.Show(fsoDelegate.Invoke("C:\Windows"))
#End Region
End Sub
My Delegate creator function:
Public Function GetDelegateFromCOM(comObj As Object, methodName As String) As GetDriveNameDelegate
Dim result As Type
CType(comObj, IDispatchInfo).GetTypeInfo(0, 0, result)
Dim mi As MethodInfo = result.GetMethod(methodName)
Return [Delegate].CreateDelegate(GetType(GetDriveNameDelegate), mi, True)
End Function
The IDispatch Interface:
<ComImport>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
<Guid("00020400-0000-0000-C000-000000000046")>
Public Interface IDispatchInfo
''' <summary>
''' Gets the number of Types that the object provides (0 or 1).
''' </summary>
''' <param name="typeInfoCount">Returns 0 or 1 for the number of Types provided by <see cref="GetTypeInfo"/>.</param>
''' <remarks>
''' http://msdn.microsoft.com/en-us/library/da876d53-cb8a-465c-a43e-c0eb272e2a12(VS.85)
''' </remarks>
<PreserveSig>
Function GetTypeInfoCount(ByRef typeInfoCount As Integer) As Integer
''' <summary>
''' Gets the Type information for an object if <see cref="GetTypeInfoCount"/> returned 1.
''' </summary>
''' <param name="typeInfoIndex">Must be 0.</param>
''' <param name="lcid">Typically, LOCALE_SYSTEM_DEFAULT (2048).</param>
''' <param name="typeInfo">Returns the object's Type information.</param>
''' <remarks>
''' http://msdn.microsoft.com/en-us/library/cc1ec9aa-6c40-4e70-819c-a7c6dd6b8c99(VS.85)
''' </remarks>
Sub GetTypeInfo(typeInfoIndex As Integer, lcid As Integer, <MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef:=GetType(TypeToTypeInfoMarshaler))> ByRef typeInfo As Type)
''' <summary>
''' Gets the DISPID of the specified member name.
''' </summary>
''' <param name="riid">Must be IID_NULL. Pass a copy of Guid.Empty.</param>
''' <param name="name">The name of the member to look up.</param>
''' <param name="nameCount">Must be 1.</param>
''' <param name="lcid">Typically, LOCALE_SYSTEM_DEFAULT (2048).</param>
''' <param name="dispId">If a member with the requested <paramref name="name"/>
''' is found, this returns its DISPID and the method's return value is 0.
''' If the method returns a non-zero value, then this parameter's output value is
''' undefined.</param>
''' <returns>Zero for success. Non-zero for failure.</returns>
''' <remarks>
''' http://msdn.microsoft.com/en-us/library/6f6cf233-3481-436e-8d6a-51f93bf91619(VS.85)
''' </remarks>
<PreserveSig>
Function GetDispId(ByRef riid As Guid, ByRef name As String, nameCount As Integer, lcid As Integer, ByRef dispId As Integer) As Integer
' NOTE: The real IDispatch also has an Invoke method next, but we don't need it.
' We can invoke methods using .NET's Type.InvokeMember method with the special
' [DISPID=n] syntax for member "names", or we can get a .NET Type using GetTypeInfo
' and invoke methods on that through reflection.
' Type.InvokeMember: http://msdn.microsoft.com/en-us/library/de3dhzwy.aspx
End Interface
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
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.
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
I have inherited a class in vb.net and when I create the object, I am only seeing one of the inherited public properties in intellisense. Any solution to this problem?
print("Public Class CompanyMailMessage
Inherits MailMessage
Private AdobeDisclaimer As String = "You will need Adobe Acrobat to read this file. If it is not installed on your computer go to http://www.adobe.com/support/downloads/main.html to download. Thank You"
Private _Body As String
Private _IncludeAdobeDisclaimer As Boolean = False
''' <summary>
''' Gets or sets the body of the message
''' </summary>
''' <returns>A System.String that contains the body content.</returns>
Public Property Body() As String
Get
If _IncludeAdobeDisclaimer Then
_Body = _Body + AdobeDisclaimer
End If
Return _Body
End Get
Set(ByVal value As String)
_Body = value
End Set
End Property
''' <summary>
''' Gets or sets a value that determines if a message that states that Adobe Acrobat must be used to open the attached files is included in the body of the message
''' </summary>
''' <value></value>
''' <returns>True if ;otherwise, false</returns>
''' <remarks></remarks>
Public Property IncludeAdobeDisclaimer() As Boolean
Get
Return _IncludeAdobeDisclaimer
End Get
Set(ByVal value As Boolean)
_IncludeAdobeDisclaimer = value
End Set
End Property
''' <summary>
''' Initializes an instance of the CompanyMailMessageclass
''' </summary>
''' <remarks></remarks>
Public Sub New()
End Sub
''' <summary>
''' Initializes an instance of the CompanyMailMessageclass with plain text in the body
''' </summary>
''' <param name="from">The email address of the sender</param>
''' <param name="fromName">The name of the sender</param>
''' <param name="to"></param>
''' <param name="subject"></param>
''' <param name="body"></param>
''' <remarks></remarks>
Public Sub New(from as String,fromName As String,[to] as String,subject As String,body As String)
MyBase.FromAddress = New EmailAddress(from,fromName)
MyBase.ToAddresses.Add([to])
MyBase.Subject = subject
_Body = body
MyBase.Items.Add(New MessageContent(MimeType.MessageRfc822,body))
End Sub");
I would suggest opening Reflector and opening the 3rd party dll. I'm guessing the properties will be internal (friend in vb.net, I think) and that's the reason.