I tried to print but the result of the printing status did not print immediately and the print time was approximately 10-12 seconds whether there is a solution so that it can be printed immediately or there is a need to be in the settings on my form
thanks
Public Shared Function SendBytesToPrinter(ByVal szPrinterName As String, ByVal pBytes As IntPtr, ByVal dwCount As Int32) As Boolean
Dim dwError As Int32 = 0, dwWritten As Int32 = 0
Dim hPrinter As New IntPtr(0)
Dim di As New DOCINFOA()
Dim bSuccess As Boolean = False ' Assume failure unless you specifically succeed.
di.pDocName = "OUTPUTPRN"
di.pDataType = "RAW"
' Open the printer.
If OpenPrinter(szPrinterName.Normalize(), hPrinter, IntPtr.Zero) Then
' Start a document.
If StartDocPrinter(hPrinter, 1, di) Then
' Start a page.
If StartPagePrinter(hPrinter) Then
' Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, dwWritten)
EndPagePrinter(hPrinter)
End If
EndDocPrinter(hPrinter)
End If
ClosePrinter(hPrinter)
End If
' If you did not succeed, GetLastError may give more information
' about why not.
If bSuccess = False Then
dwError = Marshal.GetLastWin32Error()
End If
Return bSuccess
End Function
Public Shared Function SendFileToPrinter(ByVal printerName As String, ByVal filePath As String) As Boolean
Dim bytes = File.ReadAllBytes(filePath).ToArray
Dim byteCount = bytes.Length
Dim unmanagedBytesPointer = Marshal.AllocCoTaskMem(byteCount)
Marshal.Copy(bytes, 0, unmanagedBytesPointer, byteCount)
Dim success = SendBytesToPrinter(printerName, unmanagedBytesPointer, byteCount)
Marshal.FreeCoTaskMem(unmanagedBytesPointer)
Return success
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Settings.close = True Then
Dim printer As String = "EPSON LX-300+II ESC/P"
Dim path As String = "C:\vDos\#LPT1.asc"
For i As Integer = 1 To 1
SendFileToPrinter(printer, path)
Next i
Me.Close()
End If
End Sub
Related
I tried to load mp3 from Resource and it success. But I want loop playback
I search around and found nothing...
Here's the code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim mp3 As MemoryStream = New MemoryStream(My.Resources.RequiemAtDusk)
Dim read As Mp3FileReader = New Mp3FileReader(mp3)
Dim waveOut As WaveOut = New WaveOut
waveOut.Init(read)
waveOut.Play()
End Sub
So I did it:
Public Class LoopStream
Inherits WaveStream
Private sourceStream As WaveStream
Public Sub New(ByVal sourceStream As WaveStream)
Me.sourceStream = sourceStream
Me.EnableLooping = True
End Sub
Public Property EnableLooping As Boolean
Public Overrides ReadOnly Property WaveFormat As WaveFormat
Get
Return sourceStream.WaveFormat
End Get
End Property
Public Overrides ReadOnly Property Length As Long
Get
Return sourceStream.Length
End Get
End Property
Public Overrides Property Position As Long
Get
Return sourceStream.Position
End Get
Set(ByVal value As Long)
sourceStream.Position = value
End Set
End Property
Public Overrides Function Read(ByVal buffer As Byte(), ByVal offset As Integer, ByVal count As Integer) As Integer
Dim totalBytesRead As Integer = 0
While totalBytesRead < count
Dim bytesRead As Integer = sourceStream.Read(buffer, offset + totalBytesRead, count - totalBytesRead)
If bytesRead = 0 Then
If sourceStream.Position = 0 OrElse Not EnableLooping Then
Exit While
End If
sourceStream.Position = 0
End If
totalBytesRead += bytesRead
End While
Return totalBytesRead
End Function
End Class
Loopin MP3 from resources time!
Private waveOut As WaveOut
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If waveOut Is Nothing Then
Dim mp3file As MemoryStream = New MemoryStream(My.Resources.RequiemAtDusk) '' You can use your MP3 file here
Dim reader As Mp3FileReader = New Mp3FileReader(mp3file)
Dim [loop] As LoopStream = New LoopStream(reader)
waveOut = New WaveOut()
waveOut.Init([loop])
waveOut.Play()
Else
waveOut.[Stop]()
waveOut.Dispose()
waveOut = Nothing
End If
End Sub
I am creating a file downloader using backgroundworker & i want to save the progress of backgroundworker so that when i restart the application, on resume, it start the download where i closed last time.
Any help ?
Here is My code for Downloader
Public Class cls_FileDownloader
Dim FileSave As String
Delegate Sub DownloadFIlesafe(ByVal Cancelled As Boolean)
Delegate Sub ChangeTextsSafe(ByVal length As Long, ByVal position As Double, ByVal percent As Long, ByVal speed As Long)
Private Sub cls_FileDownloader_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = ""
btn_Cancel.Enabled = False
End Sub
Private Sub btn_Download_Click(sender As Object, e As EventArgs) Handles btn_Download.Click
If Me.txt_Url.Text <> "" Then
Me.SaveFile.FileName = txt_Url.Text.Split("\"c)(txt_Url.Text.Split("\"c).Length - 1)
If SaveFile.ShowDialog = System.Windows.Forms.DialogResult.OK Then
FileSave = SaveFile.FileName
SaveFile.FileName = ""
lbl_SaveTO.Text = "Save To:" & FileSave
txt_Url.Enabled = False
btn_Download.Enabled = False
btn_Cancel.Enabled = True
bg_Worker.RunWorkerAsync()
End If
Else
MessageBox.Show("Please Insert valid file path", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
Private Sub bg_Worker_DoWork(sender As Object, e As DoWorkEventArgs) Handles bg_Worker.DoWork
Dim response As FileWebResponse
Dim request As FileWebRequest
Try
request = WebRequest.Create(txt_Url.Text)
response = request.GetResponse
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Dim cancelDelegate As New DownloadFIlesafe(AddressOf Download_Complete)
Me.Invoke(cancelDelegate, True)
Exit Sub
End Try
Dim length As Long = response.ContentLength
Dim safedelegate As New ChangeTextsSafe(AddressOf ChangeTexts)
Me.Invoke(safedelegate, length, 0, 0, 0)
Dim writeStream As New IO.FileStream(Me.FileSave, IO.FileMode.Create)
Dim nRead As Double
'To calculate the download speed
Dim speedtimer As New Stopwatch
Dim currentspeed As Long = -1
Dim readings As Integer = 0
Do
If bg_Worker.CancellationPending Then 'If user abort download
Exit Do
End If
speedtimer.Start()
Dim readBytes(4095) As Byte
Dim bytesread As Long = response.GetResponseStream.Read(readBytes, 0, 4096)
nRead += bytesread
Dim percent As Long = (nRead * 100) / length
Me.Invoke(safedelegate, length, nRead, percent, currentspeed)
If bytesread = 0 Then Exit Do
writeStream.Write(readBytes, 0, bytesread)
speedtimer.Stop()
readings += 1
If readings >= 5 Then 'For increase precision, the speed it's calculated only every five cicles
currentspeed = 20480 / (speedtimer.ElapsedMilliseconds / 1000)
speedtimer.Reset()
readings = 0
End If
Loop
'Close the streams
response.GetResponseStream.Close()
writeStream.Close()
If Me.bg_Worker.CancellationPending Then
IO.File.Delete(Me.FileSave)
Dim cancelDelegate As New DownloadFIlesafe(AddressOf Download_Complete)
Me.Invoke(cancelDelegate, True)
Exit Sub
End If
Dim completeDelegate As New DownloadFIlesafe(AddressOf Download_Complete)
Me.Invoke(completeDelegate, False)
End Sub
This question may have been asked before but im just starting out with VB.Net and was given this application to fix that uses the webcam of the pc/ tablet but I cant figure out the pinvoke error
here is my code:
Imports System.IO
Public Class frm
CaptureWebCam
Const CAP As Short = &H400S
Const CAP_DRIVER_CONNECT As Integer = CAP + 10
Const CAP_DRIVER_DISCONNECT As Integer = CAP + 11
Const CAP_EDIT_COPY As Integer = CAP + 30
Const CAP_SET_PREVIEW As Integer = CAP + 50
Const CAP_SET_PREVIEWRATE As Integer = CAP + 52
Const CAP_SET_SCALE As Integer = CAP + 53
Const WS_CHILD As Integer = &H40000000
Const WS_VISIBLE As Integer = &H10000000
Const SWP_NOMOVE As Short = &H2S
Const SWP_NOSIZE As Short = 1
Const SWP_NOZORDER As Short = &H4S
Const HWND_BOTTOM As Short = 1
Dim iDevice As Integer = 0 ' Normal device ID
Dim hHwnd As Integer ' Handle value to preview window
Public image_base64String As String
' Declare function from AVI capture DLL.
Declare Auto Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Object) As Integer
Declare Auto Function SetWindowPos Lib "user32" Alias "SetWindowPos" (ByVal hwnd As Integer, ByVal hWndInsertAfter As Integer, ByVal x As Integer, ByVal y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As Integer) As Integer
Declare Auto Function DestroyWindow Lib "user32" (ByVal hndw As Integer) As Boolean
Declare Auto Function capCreateCaptureWindowA Lib "avicap32.dll" (ByVal lpszWindowName As String, ByVal dwStyle As Integer, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Short, ByVal hWndParent As Integer, ByVal nID As Integer) As Integer
Private Sub OpenForm()
Dim iHeight As Integer = picCapture.Height
Dim iWidth As Integer = picCapture.Width
' Open Preview window in picturebox .
' Create a child window with capCreateCaptureWindowA so you can display it in a picturebox.
hHwnd = capCreateCaptureWindowA(iDevice, WS_VISIBLE Or WS_CHILD, 0, 0, 600, 480, picCapture.Handle, IntPtr.Zero)
' Connect to device
If SendMessage(hHwnd, CAP_DRIVER_CONNECT, iDevice, IntPtr.Zero) Then
' Set the preview scale
SendMessage(hHwnd, CAP_SET_SCALE, True, IntPtr.Zero)
' Set the preview rate in milliseconds
SendMessage(hHwnd, CAP_SET_PREVIEWRATE, 66, IntPtr.Zero)
' Start previewing the image from the camera
SendMessage(hHwnd, CAP_SET_PREVIEW, True, IntPtr.Zero)
' Resize window to fit in picturebox
SetWindowPos(hHwnd, HWND_BOTTOM, 0, 0, picCapture.Width, picCapture.Height, SWP_NOMOVE Or SWP_NOZORDER)
Else
' Error connecting to device close window
DestroyWindow(hHwnd)
End If
End Sub
Private Function btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCapture.Click
Dim data As IDataObject
Dim bmap As Image
' Copy image to clipboard
SendMessage(hHwnd, CAP_EDIT_COPY, 0, 0)
' Get image from clipboard and convert it to a bitmap
data = Clipboard.GetDataObject()
If data.GetDataPresent(GetType(System.Drawing.Bitmap)) Then
bmap = CType(data.GetData(GetType(System.Drawing.Bitmap)), Image)
picCapture.Image = bmap
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Jpeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif"
saveFileDialog1.Title = "Save an Image File"
saveFileDialog1.FileName = "Image001"
If saveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
' If the file name is not an empty string open it for saving.
If saveFileDialog1.FileName <> "" Then
' Saves the Image via a FileStream created by the OpenFile method.
Dim fs As System.IO.FileStream = CType(saveFileDialog1.OpenFile(), System.IO.FileStream)
picCapture.Image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg)
fs.Close()
End If
End If
End If
End Function
Public Function getImage() As String
Dim bmap As Image
Dim ms As New MemoryStream
bmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim bytes() As Byte = ms.ToArray
' Dim image_base64String As String = Convert.ToBase64String(bytes)
image_base64String = Convert.ToBase64String(bytes)
'MsgBox(image_base64String)
Return image_base64String
End Function
Private Sub frmcap_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Leave
' Disconnect from device
SendMessage(hHwnd, CAP_DRIVER_DISCONNECT, iDevice, 0)
' close window
DestroyWindow(hHwnd)
End Sub
Private Sub frmCaptureWebCam_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OpenForm()
End Sub
End Class
you will notice that I'm also trying to return the image via the image_base64 variable
Can someone help me with the code as I get the following error:
PInvokeStackImbalance was detected
Message: A call to PInvoke function
'GCOS3_Mobile_Host_Application!GCOS3_Mobile_Host_Application.frmCaptureWebCam::SendMessage'
has unbalanced the stack. This is likely because the managed PInvoke
signature does not match the unmanaged target signature. Check that
the calling convention and parameters of the PInvoke signature match
the target unmanaged signature.
SendMessage declaration according to pinvoke should be like this
Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
Also see the tips for Overloads there.
In your code you have declared lParam, which provides additional message-specific information, as object.
And you are passing IntPtr.Zero, so I think using ByVal lParam As IntPtr will be more specific.
I used the emgu library and got it to return the base 64 string:
Imports Emgu.CV
Imports Emgu.CV.Util
Imports System.IO
Public Class frmEmguCapture
Private imagecapture As Capture
Private imageCaptureReady As Boolean = False
Public b64 As String
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles tmrUpdateImage.Tick
tmrUpdateImage.Enabled = False
If imageCaptureReady Then
pbWebCamStream.Visible = True
lblConnecting.Visible = False
btnCapture.Enabled = True
pbWebCamStream.Image = imagecapture.QueryFrame.Bitmap
tmrUpdateImage.Enabled = True
Else
MessageBox.Show("Error connecting to camera.", "Error conecting to camera.", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
End Sub
Public Function btnCapture_Click(sender As Object, e As EventArgs) Handles btnCapture.Click
tmrUpdateImage.Enabled = False
pbWebCamStream.Visible = True
lblConnecting.Visible = False
btnCapture.Enabled = True
pbWebCamStream.Image = imagecapture.QueryFrame.Bitmap
Dim bmap As Image
bmap = imagecapture.QueryFrame.Bitmap
Dim ms As New MemoryStream
bmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim bytes() As Byte = ms.ToArray
Dim image_base64String As String = Convert.ToBase64String(bytes)
image_base64String = Convert.ToBase64String(bytes)
b64 = image_base64String
imagecapture.Dispose()
Me.Close()
'MsgBox(image_base64String)
Return image_base64String
End Function
Private Sub frmEmguCapture_Load(sender As Object, e As EventArgs) Handles MyBase.Load
tmrLoad.Enabled = True
End Sub
Private Sub tmrLoad_Tick(sender As Object, e As EventArgs) Handles tmrLoad.Tick
tmrLoad.Enabled = False
Try
imagecapture = New Capture
imageCaptureReady = True
tmrUpdateImage.Enabled = True
Catch ex As Exception
MessageBox.Show("Error connecting to camera.", "Error conecting to camera.", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
End Sub
End Class
I found one code which auto-change proxies from own text file located in computer.
Now I would like to rather this get path from my own URL where I store my private list of proxies, so what I have to change in the code please? and could also someone explain why? thank you.
Imports System
Imports System.Runtime.InteropServices
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Timers
Public Class Form1
Dim FILE_NAME As String = "C:\Users\name\Documents\proxylist.txt"
Dim label As String
Public proxy(2000) As String
Public index As Integer = 0
Public max_proxys As Integer = 0
Dim a As String
Dim start_check As Integer = 0
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (start_check > 0) Then
index = 0
Do While index <> max_proxys
proxy(index) = ""
index = index + 1
Loop
If TextBox3.Text = "" Then
FILE_NAME = "C:\Users\name\Documents\proxylist.txt"
End If
End If
If TextBox3.Text <> "" Then
FILE_NAME = TextBox3.Text
End If
Try
Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(FILE_NAME)
index = 0
Do While reader.Peek <> -1
a = reader.ReadLine
proxy(index) = a.ToString
index = index + 1
Loop
max_proxys = index
reader.Close()
Catch ex As Exception
MessageBox.Show("File Not Found")
Timer1.Stop()
End Try
label = "true"
index = 0
TextBox1.Text = proxy(0)
If TextBox2.Text = "" Then
Timer1.Interval = 1000 'ms
Else
Try
Dim a As Integer = Convert.ToDecimal(TextBox2.Text)
Timer1.Interval = a * 1000 'ms
Catch ex As Exception
MessageBox.Show(ex.Message & "Please Enter Valid Time in Seconds ")
If Timer1.Enabled Then
Timer1.Stop()
End If
End Try
End If
start_check = 1
Timer1.Start()
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
label = "false"
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim clsProxy As New IEProxy
clsProxy.DisableProxy()
End Sub
Private Sub Timer1_Tick_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
TextBox1.Text = proxy(index)
index = index + 1
Dim clsProxy As New IEProxy
If clsProxy.SetProxy(TextBox1.Text) Then
MessageBox.Show("Proxy successfully enabled.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Error enabling proxy.", "Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
If index >= max_proxys Then
index = 0
End If
If label.Equals("false") Then
Timer1.Stop()
End If
End Sub
End Class
Public Class IEProxy
Public Enum Options
INTERNET_PER_CONN_FLAGS = 1
INTERNET_PER_CONN_PROXY_SERVER = 2
INTERNET_PER_CONN_PROXY_BYPASS = 3
INTERNET_PER_CONN_AUTOCONFIG_URL = 4
INTERNET_PER_CONN_AUTODISCOVERY_FLAGS = 5
INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_PER_CONNECTION_OPTION = 75
INTERNET_OPTION_SETTINGS_CHANGED = 39
PROXY_TYPE_PROXY = &H2
PROXY_TYPE_DIRECT = &H1
End Enum
<StructLayout(LayoutKind.Sequential)> _
Private Class FILETIME
Public dwLowDateTime As Integer
Public dwHighDateTime As Integer
End Class
<StructLayout(LayoutKind.Explicit, Size:=12)> _
Private Structure INTERNET_PER_CONN_OPTION
<FieldOffset(0)> Dim dwOption As Integer
<FieldOffset(4)> Dim dwValue As Integer
<FieldOffset(4)> Dim pszValue As IntPtr
<FieldOffset(4)> Dim ftValue As IntPtr
Public Function GetBytes() As Byte()
Dim b(12) As Byte
BitConverter.GetBytes(dwOption).CopyTo(b, 0)
Select Case dwOption
Case Options.INTERNET_PER_CONN_FLAGS
BitConverter.GetBytes(dwValue).CopyTo(b, 4)
Case Options.INTERNET_PER_CONN_PROXY_BYPASS
BitConverter.GetBytes(pszValue.ToInt32()).CopyTo(b, 4)
Case Options.INTERNET_PER_CONN_PROXY_SERVER
BitConverter.GetBytes(pszValue.ToInt32()).CopyTo(b, 4)
End Select
Return b
End Function
End Structure
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
Private Class INTERNET_PER_CONN_OPTION_LIST
Public dwSize As Integer
Public pszConnection As String
Public dwOptionCount As Integer
Public dwOptionError As Integer
Public pOptions As IntPtr
End Class
<StructLayout(LayoutKind.Sequential)> _
Private Class INTERNET_PROXY_INFO
Public dwAccessType As Integer
Public lpszProxy As IntPtr
Public lpszProxyBypass As IntPtr
End Class
Private Const ERROR_INSUFFICIENT_BUFFER = 122
Private Const INTERNET_OPTION_PROXY = 38
Private Const INTERNET_OPEN_TYPE_DIRECT = 1
<DllImport("wininet.dll")> _
Private Shared Function InternetSetOption(ByVal hInternet As IntPtr, _
ByVal dwOption As Integer, _
ByVal lpBuffer As INTERNET_PER_CONN_OPTION_LIST, _
ByVal dwBufferLength As Integer) As Boolean
End Function
<DllImport("kernel32.dll")> _
Private Shared Function GetLastError() As Integer
End Function
Public Function SetProxy(ByVal proxy_full_addr As String) As Boolean
Dim bReturn As Boolean
Dim list As New INTERNET_PER_CONN_OPTION_LIST
Dim dwBufSize As Integer = Marshal.SizeOf(list)
Dim opts(3) As INTERNET_PER_CONN_OPTION
Dim opt_size As Integer = Marshal.SizeOf(opts(0))
list.dwSize = dwBufSize
list.pszConnection = ControlChars.NullChar
list.dwOptionCount = 3
'set flags
opts(0).dwOption = Options.INTERNET_PER_CONN_FLAGS
opts(0).dwValue = Options.PROXY_TYPE_DIRECT Or Options.PROXY_TYPE_PROXY
'set proxyname
opts(1).dwOption = Options.INTERNET_PER_CONN_PROXY_SERVER
opts(1).pszValue = Marshal.StringToHGlobalAnsi(proxy_full_addr)
'set override
opts(2).dwOption = Options.INTERNET_PER_CONN_PROXY_BYPASS
opts(2).pszValue = Marshal.StringToHGlobalAnsi("local")
Dim b(3 * opt_size) As Byte
opts(0).GetBytes().CopyTo(b, 0)
opts(1).GetBytes().CopyTo(b, opt_size)
opts(2).GetBytes().CopyTo(b, 2 * opt_size)
Dim ptr As IntPtr = Marshal.AllocCoTaskMem(3 * opt_size)
Marshal.Copy(b, 0, ptr, 3 * opt_size)
list.pOptions = ptr
'Set the options on the connection
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_PER_CONNECTION_OPTION, list, dwBufSize)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
'Notify existing Internet Explorer instances that the settings have changed
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_SETTINGS_CHANGED, Nothing, 0)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
'Flush the current IE proxy setting
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_REFRESH, Nothing, 0)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
Marshal.FreeHGlobal(opts(1).pszValue)
Marshal.FreeHGlobal(opts(2).pszValue)
Marshal.FreeCoTaskMem(ptr)
Return bReturn
End Function
Public Function DisableProxy() As Boolean
Dim bReturn As Boolean
Dim list As New INTERNET_PER_CONN_OPTION_LIST
Dim dwBufSize As Integer = Marshal.SizeOf(list)
Dim opts(0) As INTERNET_PER_CONN_OPTION
Dim opt_size As Integer = Marshal.SizeOf(opts(0))
list.dwSize = dwBufSize
list.pszConnection = ControlChars.NullChar
list.dwOptionCount = 1
opts(0).dwOption = Options.INTERNET_PER_CONN_FLAGS
opts(0).dwValue = Options.PROXY_TYPE_DIRECT
Dim b(opt_size) As Byte
opts(0).GetBytes().CopyTo(b, 0)
Dim ptr As IntPtr = Marshal.AllocCoTaskMem(opt_size)
Marshal.Copy(b, 0, ptr, opt_size)
list.pOptions = ptr
'Set the options on the connection
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_PER_CONNECTION_OPTION, list, dwBufSize)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
'Notify existing Internet Explorer instances that the settings have changed
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_SETTINGS_CHANGED, Nothing, 0)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
'Flush the current IE proxy setting
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_REFRESH, Nothing, 0)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
Marshal.FreeCoTaskMem(ptr)
Return bReturn
End Function
End Class
Maybe just download your url to the FILE_NAME location in your form's load event. Be warned that if there is a file at FILE_NAME, this sub I provide you will overwrite it.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim YourURL As String = "http://www.yoururl.com/filename.ext"
Using w As New System.Net.WebClient
w.DownloadFile(YourURL, FILE_NAME)
End Using
End Sub
I am making a simple tcp communication program just to send strings I keep reciving
Only one usage of each socket address (protocol/network address/port) is normally permitted
I have run the exact same code on windows 8, in witch case it works fine, but on 7 i get this error.( I need it to run on 7)
here is my code( It is a fake virus not intended for any harm):
{
Imports IWshRuntimeLibrary
Public Class Form1
Dim virus As Boolean = False
'Public IsClosing As Boolean = False
Private _Server As New TcpCommServer(AddressOf UpdateUI)
Private _Server2 As New TcpCommServer(AddressOf UpdateUI2)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
_Server.Start(32800)
_Server2.Start(32801)
If My.Settings.autostart = False Then
Dim startupPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim executablePath As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
Dim executableName As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName
'create shortcut
Dim Shell As WshShell
Dim Link As WshShortcut
Try
Shell = New WshShell
Link = CType(Shell.CreateShortcut(startupPath & "\" & executableName & ".lnk"), IWshShortcut)
Link.TargetPath = executablePath
Link.Save()
Catch ex As Exception
MsgBox(ex.Message)
End Try
My.Settings.autostart = True
ElseIf My.Settings.autostart = True Then
End If
End Sub
Private Function BytesToString(ByVal data() As Byte) As String
Dim enc As New System.Text.UTF8Encoding()
BytesToString = enc.GetString(data)
End Function
Private Function StrToByteArray(ByVal text As String) As Byte()
Dim encoding As New System.Text.UTF8Encoding()
StrToByteArray = encoding.GetBytes(text)
End Function
Private Function BytesToString2(ByVal data() As Byte) As String
Dim enc2 As New System.Text.UTF8Encoding()
BytesToString2 = enc2.GetString(data)
End Function
Private Function StrToByteArray2(ByVal text As String) As Byte()
Dim encoding2 As New System.Text.UTF8Encoding()
StrToByteArray2 = encoding2.GetBytes(text)
End Function
Public Sub UpdateUI(ByVal bytes() As Byte, ByVal sessionID As Int32, ByVal dataChannel As Integer)
If Me.InvokeRequired() Then
' InvokeRequired: We're running on the background thread. Invoke the delegate.
Me.Invoke(_Server.ServerCallbackObject, bytes, sessionID, dataChannel)
Else
' We're on the main UI thread now.
If dataChannel = 1 Then
Me.lbtextinput.Text = (BytesToString(bytes))
ElseIf dataChannel = 255 Then
Dim tmp = ""
Dim msg As String = BytesToString(bytes)
Dim dontReport As Boolean = False
' _Server as finished sending the bytes you put into sendBytes()
If msg.Length > 3 Then tmp = msg.Substring(0, 3)
If tmp = "UBS" Then ' User Bytes Sent.
Dim parts() As String = Split(msg, "UBS:")
msg = "Data sent to session: " & parts(1)
End If
End If
End If
End Sub
Public Sub UpdateUI2(ByVal bytes() As Byte, ByVal sessionID As Int32, ByVal dataChannel As Integer)
If Me.InvokeRequired() Then
' InvokeRequired: We're running on the background thread. Invoke the delegate.
Me.Invoke(_Server2.ServerCallbackObject, bytes, sessionID, dataChannel)
Else
' We're on the main UI thread now.
If dataChannel = 1 Then
MsgBox(BytesToString2(bytes))
ElseIf dataChannel = 255 Then
Dim tmp = ""
Dim msg As String = BytesToString2(bytes)
Dim dontReport As Boolean = False
' _Server as finished sending the bytes you put into sendBytes()
If msg.Length > 3 Then tmp = msg.Substring(0, 3)
If tmp = "UBS" Then ' User Bytes Sent.
Dim parts() As String = Split(msg, "UBS:")
msg = "Data sent to session: " & parts(1)
End If
End If
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If lbtextinput.Text = "Start Virus" Then
virus = True
ElseIf lbtextinput.Text = "Stop Virus" Then
virus = False
End If
End Sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
If virus = True Then
Form2.Show()
Else
Form2.Hide()
End If
End Sub
End Class
} Form1
Now a linked class {
Imports System.IO
Imports System.Runtime.InteropServices
Public Class clsAsyncUnbuffWriter
Public Class clsSystemInfo
Private Class WinApi
<DllImport("kernel32.dll")> _
Public Shared Sub GetSystemInfo(<MarshalAs(UnmanagedType.Struct)> ByRef lpSystemInfo As SYSTEM_INFO)
End Sub
<StructLayout(LayoutKind.Sequential)> _
Public Structure SYSTEM_INFO
Friend uProcessorInfo As _PROCESSOR_INFO_UNION
Public dwPageSize As UInteger
Public lpMinimumApplicationAddress As IntPtr
Public lpMaximumApplicationAddress As IntPtr
Public dwActiveProcessorMask As IntPtr
Public dwNumberOfProcessors As UInteger
Public dwProcessorType As UInteger
Public dwAllocationGranularity As UInteger
Public dwProcessorLevel As UShort
Public dwProcessorRevision As UShort
End Structure
<StructLayout(LayoutKind.Explicit)> _
Public Structure _PROCESSOR_INFO_UNION
<FieldOffset(0)> _
Friend dwOemId As UInteger
<FieldOffset(0)> _
Friend wProcessorArchitecture As UShort
<FieldOffset(2)> _
Friend wReserved As UShort
End Structure
End Class
Public Shared Function GetPageSize() As Integer
Dim sysinfo As New WinApi.SYSTEM_INFO()
WinApi.GetSystemInfo(sysinfo)
Return CInt(sysinfo.dwPageSize)
End Function
End Class
Private target As FileStream
Private inputBuffer As MemoryStream
Private bufferSize As Integer
Private running As Boolean
Private writing As Boolean
Private readWait As Threading.ManualResetEvent
Private writeWait As Threading.ManualResetEvent
Private finishedWriting As Threading.ManualResetEvent
Private totalWritten As Int64
Private writeTimer As Stopwatch
Public Function GetTotalBytesWritten() As Int64
Return totalWritten
End Function
Public Function IsRunning() As Boolean
Return running
End Function
Public Sub Close()
writing = False
writeWait.Set()
finishedWriting.WaitOne()
readWait.Set()
End Sub
Public Function GetActiveMiliseconds() As Int64
Try
Return writeTimer.ElapsedMilliseconds
Catch ex As Exception
Return 0
End Try
End Function
Public Shared Function GetPageSize() As Integer
Return clsSystemInfo.GetPageSize
End Function
Public Sub New(ByVal dest As String, _
Optional ByVal unbuffered As Boolean = False, _
Optional ByVal _bufferSize As Integer = (1024 * 1024), _
Optional ByVal setLength As Int64 = 0)
bufferSize = _bufferSize
Dim options As FileOptions = FileOptions.SequentialScan
If unbuffered Then options = FileOptions.WriteThrough Or FileOptions.SequentialScan
readWait = New Threading.ManualResetEvent(False)
writeWait = New Threading.ManualResetEvent(False)
finishedWriting = New Threading.ManualResetEvent(False)
readWait.Set()
writeWait.Reset()
finishedWriting.Reset()
target = New FileStream(dest, _
FileMode.Create, FileAccess.Write, FileShare.None, GetPageSize, options)
If setLength > 0 Then target.SetLength(setLength)
totalWritten = 0
inputBuffer = New MemoryStream(bufferSize)
running = True
writing = True
writeTimer = New Stopwatch
Dim asyncWriter As New Threading.Thread(AddressOf WriteThread)
With asyncWriter
.Priority = Threading.ThreadPriority.Lowest
.IsBackground = True
.Name = "AsyncCopy writer"
.Start()
End With
End Sub
Public Function Write(ByVal someBytes() As Byte, ByVal numToWrite As Integer) As Boolean
If Not running Then Return False
If numToWrite < 1 Then Return False
If numToWrite > inputBuffer.Capacity Then
Throw New Exception("clsAsyncUnbuffWriter: someBytes() can not be larger then buffer capacity")
End If
If (inputBuffer.Length + numToWrite) > inputBuffer.Capacity Then
If inputBuffer.Length > 0 Then
readWait.Reset()
writeWait.Set()
readWait.WaitOne()
If Not running Then Return False
inputBuffer.Write(someBytes, 0, numToWrite)
End If
Else
inputBuffer.Write(someBytes, 0, numToWrite)
End If
Return True
End Function
Private Sub WriteThread()
Dim bytesThisTime As Int32 = 0
Dim internalBuffer(bufferSize) As Byte
writeTimer.Stop()
writeTimer.Reset()
writeTimer.Start()
Do
writeWait.WaitOne()
writeWait.Reset()
bytesThisTime = CInt(inputBuffer.Length)
Buffer.BlockCopy(inputBuffer.GetBuffer, 0, internalBuffer, 0, bytesThisTime)
inputBuffer.SetLength(0)
readWait.Set()
target.Write(internalBuffer, 0, bytesThisTime)
totalWritten += bytesThisTime
Loop While writing
' Flush inputBuffer
If inputBuffer.Length > 0 Then
bytesThisTime = CInt(inputBuffer.Length)
Buffer.BlockCopy(inputBuffer.GetBuffer, 0, internalBuffer, 0, bytesThisTime)
target.Write(internalBuffer, 0, bytesThisTime)
totalWritten += bytesThisTime
End If
running = False
writeTimer.Stop()
finishedWriting.Set()
Try
target.Close()
target.Dispose()
Catch ex As Exception
End Try
inputBuffer.Close()
inputBuffer.Dispose()
inputBuffer = Nothing
internalBuffer = Nothing
target = Nothing
GC.GetTotalMemory(True)
End Sub
End Class
} Public Class clsAsyncUnbuffWriter
Now I do have one more chunk of code but it wont fit so I will post it later. all these chunks call to each other.
please help.