Locking computer drive using VB.net - vb.net

I want to create a project through which I should be able to first see my drives and then select one of them to programically lock them.
Is it possible ?
If so please answer

You can get your devices with DriveInfo.GetDrives().
How do you want to lock them? If you want to encode a folder, look at https://stackoverflow.com/a/2302028/3905529
To lock a device or folder withouth encrypting is not reliable because in this case the data are not locked at another pc.

I tested the code below extracted from http://www.mindfiresolutions.com/How-to-Lock-And-Unlock-a-Folder-through-Code-in-VBNET-2310.php. First you have to provide a way to choose the directory you want to lock, in the case shown, a folderbrowserdialog was used.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnBrowse.Click
Try
If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
TextBox1.Text = FolderBrowserDialog1.SelectedPath
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Then I created two buttons to lock and unlock the directory whose path was written in a textbox previously by the function above.
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles btnLock.Click
Dim fs As FileSystemSecurity = File.GetAccessControl(TextBox1.Text)
fs.AddAccessRule(New FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny))
File.SetAccessControl(TextBox1.Text, fs)
End Sub
Private Sub btnUnlock_Click(sender As System.Object, e As System.EventArgs) Handles btnUnlock.Click
Dim fs As FileSystemSecurity = File.GetAccessControl(TextBox1.Text)
fs.RemoveAccessRule(New FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny))
File.SetAccessControl(TextBox1.Text, fs)
End Sub
The first one locks the directory and the other unlocks it.

Related

Save the image from the picturebox

Use this code to save the image from the PictureBox.
By saving the file and adding a name to it
The problem I'm facing, come on, when adjusting the image the following error occurs : - a generic error occurred in gdi+
My Code
show image
Using fs As New System.IO.FileStream("path", IO.FileMode.Open, IO.FileAccess.Read) PIC_PARTA.Image = System.Drawing.Image.FromStream(fs) End Using
save image
Dim pic As Image
pic = PIC_PARTA.Image
Dim Savefild As New SaveFileDialog
Savefild.FileName = TEXT_NAMEIMG.Text & ".PNG"
Savefild.ShowDialog()
pic.Save(Savefild.FileName, System.Drawing.Imaging.ImageFormat.Png)
LAB_path.Text = Savefild.FileName
Savefild.Dispose()
pic.Dispose()
This is not a full answer at this stage but it includes a significant amount of code, so I'll post as an answer and then either update or delete as required.
I just tried this code and all four saves worked, even though I thought that some may not:
Imports System.IO
Public Class Form1
Private ReadOnly folderPath As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyPictures, "Test")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PictureBox1.Image = Image.FromFile(Path.Combine(folderPath, "Picture1.png"))
Using fs = File.OpenRead(Path.Combine(folderPath, "Picture2.png"))
PictureBox2.Image = Image.FromStream(fs)
End Using
PictureBox3.ImageLocation = Path.Combine(folderPath, "Picture3.png")
PictureBox4.Load(Path.Combine(folderPath, "Picture4.png"))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
PictureBox1.Image.Save(Path.Combine(folderPath, "Output1.png"))
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
PictureBox2.Image.Save(Path.Combine(folderPath, "Output2.png"))
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Try
PictureBox3.Image.Save(Path.Combine(folderPath, "Output3.png"))
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Try
PictureBox4.Image.Save(Path.Combine(folderPath, "Output4.png"))
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
End Class
Can you please test that with your own images in your own folder and see if you get the same result?
Note that the Image.FromFile option locks the file until you dispose the Image. I have seen instances in the past where trying to save an Image created using Image.FromStream generates the error message you mentioned because it can't access the stream again later. Image.FromFile avoids that but has its own downsides.
My code that uses a FileStream directly is simpler and, therefore, better than yours but setting ImageLocation or calling Load is simpler again and thus better again. I suggest that you use one of those two options and see whether you still have an issue.

Drag and Drop not working on shortcut or exefile

Drag&Drop is working correctly when application is running. But when a file is dropped on application shortcut or exe.file, no drag&drop event is triggered just aaplication starts.
I created simple application in Visual Studio 2019, only Form1 with following adjustments
Form1.AllowDrop = True
Private Sub Form1_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
Private Sub Form1_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
Dim files() As String = CType(e.Data.GetData(DataFormats.FileDrop), String())
Me.Text = files(0)
End Sub
Can you help me how to open my application with correct filename which is dropped on application icon/shortcut?
Thanks, Martin
Your code only handles the drag and drop on the form itself (which can be done with any other control with AllowDrop = True). Dropping a file onto the application executable file (or shortcut) is a totally different thing; what it does is simply open the application normally but with a command-line argument passed to it (i.e., the file/folder path).
To retrieve that file/folder path, you can use Environment.GetCommandLineArgs, to read the command-line arguments, make sure it returns at least two elements (the first one is your application's executable path), and then display the second (or second to last) elements.
This should work:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim args = Environment.GetCommandLineArgs()
If args.Length > 1 Then Me.Text = args(1)
End Sub
If you drop multiple files onto your program's icon and you want to display them all, you can adjust the above code to something like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim args = Environment.GetCommandLineArgs()
For Each arg In args.Skip(1)
' Do something with `arg`.
Next
End Sub

VB.net Printform cant find path

So I am working on a form which need to be printed. I want to end up with a PDF file using Foxit PDF printer. The problem is that I cant figure out how to get the selected path as file location so I keep getting an the Path cannot be null.
error. Where in the code should I put my filelocation when using the Printform?
In this code the foldername is the location where I want to print.
Private Sub BtnPrint_Click(sender As Object, e As EventArgs) Handles BtnPrint.Click
Dim folderDlg As New FolderBrowserDialog
Dim foldername As String
folderDlg.ShowNewFolderButton = True
If (folderDlg.ShowDialog() = DialogResult.OK) Then
foldername = folderDlg.SelectedPath
Dim root As Environment.SpecialFolder = folderDlg.RootFolder
End If
PrintForm1.Print()
End Sub
Edit:
Actually deleted part of the code and still getting the same error (first part wasnt doing anything to start with I know that). All I am using now is:
Private Sub BtnPrint_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles BtnPrint.Click
PrintForm1.Print()
End Sub
Also microsoft help database about Printform isnt helping since I have done exactly what it says and still getting the Path is Null error
Edit 2:
So I am using this code now and it is working.
Private Sub BtnPrint_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles BtnPrint.Click
PrintDialog1.PrinterSettings = PrintForm1.PrinterSettings
PrintDialog1.AllowSomePages = True
If PrintDialog1.ShowDialog = DialogResult.OK Then PrintForm1.PrinterSettings = PrintDialog1.PrinterSettings
With Me.PrintForm1
.PrintAction = Printing.PrintAction.PrintToPreview
Dim MyMargins As New Margins
With MyMargins
.Left = 10
.Right = 10
.Top = 10
.Bottom = 10
End With
.PrinterSettings.DefaultPageSettings.Margins = MyMargins
.Print()
End With
End Sub
but as soon as I try to set which area it should print I get the following error: "Printing is not a member of powerpacks". I tried using the following code according to microsoft this is the way it should work.. I have no clue where the error comes from
.Print(Me, PowerPacks.Printing.PrintForm.PrintOption.ClientAreaOnly)
You don't need a path to use printform. Printform just prints what you see on the screen to your default printer. You need to install "Visual Basic PowerPacks" to use this command. More explanation you may find here:
https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/printing/how-to-print-a-form-by-using-the-printform-component
To preview your print you don't need to use printdialog and all this. You just click on printform1 in the designer,to get up the properties window of printform1. In printaction you choose PrintToPreview. Thats all its needed.
These are all the lines I need:
Public Class Form1
Private Sub Exit_Click(sender As Object, e As EventArgs) Handles Button2.Click
Application.Exit()
End Sub
Private Sub Print_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintForm1.Print()
End Sub
End Class

How to do you make a ListBox display all files in a drive?

I'm coding an Anti-Virus at the moment, so it's been very complicated to code it and design it. Anyway, the other day I ran into a problem, where my ListBox is not displaying all the files that are in the selected drive/directory.
I'll put some code and images so you get the idea.
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
ListBox1.Items.Clear()
ListBox3.Items.Clear()
FolderBrowserDialog1.SelectedPath = Path.GetPathRoot(Environment.SystemDirectory) & "Boot\"
On Error Resume Next
For Each strDir As String In System.IO.Directory.GetDirectories(FolderBrowserDialog1.SelectedPath)
For Each strFile As String In System.IO.Directory.GetFiles(strDir)
ListBox1.Items.Add(strFile)
ListBox3.Items.Add(strFile)
Next
Next
Timer1.Start()
End Sub
However, instead of the files appearing in the ListBox (ListBox3), it just gives a black screen. Maybe I should remove the TabControl that it is surrounded by?
See how it's black? It even happens when I run it.
Hope this helps! Comment if you need more information.
You may want to simplify your events by creating subs and standardizing the code instead of embedding it directly into the button click. I have created a working example of how to load directories and files dynamically.
I would also recommend doing a isolated experiment, you can easily throw together a test project to isolate the directories in question and the layout you are trying to achieve. It could be that there are other events causing noise in your debugging.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
load_dirs(ListBox2, "H:\")
End Sub
Sub load_files(LB As ListBox,
IO_dir As String)
Dim Files_ = IO.Directory.GetFiles(IO_dir)
With LB.Items
.Clear()
.AddRange(Files_)
End With
End Sub
Sub load_dirs(LB As ListBox,
IO_dir As String)
Dim dir_ = IO.Directory.GetDirectories(IO_dir)
With LB.Items
.Clear()
.AddRange(dir_)
End With
End Sub
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
Try
Dim lb As ListBox = sender
load_files(ListBox1, lb.SelectedItem)
Catch ex As Exception
End Try
End Sub
End Class

Unable to enumerate the process modules

I was trying to make a file unlocker which get process which using the file and get it killed to make it able to be deleted. It was okay when my targeted file is a WMP file. But I can't get it work when it comes to dll and iso. I got the problem on this line:
Which is used to get the process name. Any help is appreciated.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnShow.Click
Dim files As New List(Of String)
files.Add(OpenFileDialog1.FileName)
Dim Processes As List(Of Process) = Util.GetProcessesUsingFiles(files)
RichTextBox1.AppendText(vbCrLf & "Processes that using the file is:")
For Each p As Process In Processes
TextBox1.Text = (Path.GetFileName(p.MainModule.FileName))
TextBox1.Text = TextBox1.Text.Replace(".exe", "")
Next
Timer1.Start()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnKill.Click
If TextBox1.Text = ("Nothing") Then
MsgBox("No proccess is using that file.")
ElseIf MsgBox("Proccess(es) killed") Then
End If
For Each p As Process In System.Diagnostics.Process.GetProcessesByName(Path.GetFileName(TextBox1.Text))
Try
p.Kill()
' possibly with a timeout
p.WaitForExit()
' process was terminating or can't be terminated - deal with it
Catch winException As Win32Exception
' process has already exited - might be able to let this one go
Catch invalidException As InvalidOperationException
End Try
Next
I've already got the solution. Just add Try..Catch..