Using Drag and Drop in PowerShell GUIs

Drag and drop is a wonderful facility that most of us will use every day without even thinking about it. This article shows how it can be implemented in PowerShell GUI applications.

For this particular script, we’ll implement drag and drop functionality to allow us to drag a file from explorer to a textbox in we’ve created. When the drag and drop operation is complete, the textbox will then show the path to the file.

You can find a copy of the PowerShell Studio form and exported PowerShell code at the PowerShell.Amsterdam repository.

Here is what we our application will do once we have completed it:

To achieve our objective, we need to make use of two events, DragOver, and DragDrop.

DragOver occurs when the mouse is over the control on which we wish to ‘drop’ our object. We’ll typically just use this for changing our pointer to show a move or copy operation is in operation.

DragDrop occurs once the actual operation is finished. That is, the object has been dragged into the form and over the control, and the mouse button released.

To implement this in our application, carry out the following:

  • Create a form
  • Create a Textbox on the form
  • Set the following properties for the Textbox
    • Name : txtDragandDrop
    • Label : Contents dragged:
    • AllowDrop : true

1 - form design and properties

We now define the events that will be processed, and their handlers.

  • DragDrop : txtDragandDrop_DragDrop
  • DragOver : txtDragandDrop_DragOver

2 - form design and events

For the event handler code, use the following :

If you are developing this application in PowerShell Studio, you will need to first export the code, either to a standalone EXE, or .PS1 file.

  • Run the application from either of the above.
  • Drag a file of you choice from explorer to the textbox.

The textbox will be populated with the filepath of the file that has been dragged and dropped over it.

4 - running

Thanks for reading!

Tim

Sharing Events Handlers in PowerShell GUIs

When you setup an event handler and its code, it is helpful to know it can be shared amongst multiple controls whilst still allowing access to the specific control which raised the event.

The first apparent benefit of this is that it instantly reduces the amount of code and code replication in your scripts, but it also gives an insight into what information is received by an event handler.

Although there are some exceptions, a typical event will provide two sets of information that the hander can process

  • The calling object (referenced in your code by use of the variable $this), also known as the Sender
  • The event arguments, passed in as a pipelined object $_

To illustrate how we can use this, we’re going to create a form with two buttons, which share the same event handler, which change the background color to white when the mouse hovers over it, and then back to normal when the mouse leaves the button’s area. You can find a copy of the PowerShell Studio form, and exported .ps1 file (for looking at the pure PowerShell code) at my GitHub repository

  • Create a form with two buttons
  • Select the first button
  • For the MouseHover event, call its handler buttonHover
  • For the MouseLeave event, call its handler buttonLeave
  • Repeat the button setting for the second button
Sharing Events - Force and Event Design

The first buttons configuration

Sharing Events - Force and Event Design Button 2

The second buttons configuration

  For our the event code, use the following:

Shared events in action :

Creating a Shortcut for a Button in a PowerShell GUI

While most of us are all still friends with the mouse in GUIs, keyboard shortcuts once learned are very effective ways of manipulating form controls quicker.

Serveral controls, such as buttons can use keyboard accelerators. This is simply done by prefixing the Text property of the control by an ampersand. By doing this, you can perform the same as the Click event for that control simply by holding down the ALT key on the keyboard, and then the appropriate letter.

For example, a button control with its text property set to &OK will respond to the keyboard combination ALT + O as if the mouse had clicked on it. In keeping with normal Windows functionality, you can identify the keyboard shortcut by holding down the ALT key, and the letter for the accelerator will be listed with an underline.

Here’s how you’d do this in PowerShell Studio :

Keyboard Shortcut

And in PowerShell code itself, this is represented as :

Using .NET Event Handlers in a PowerShell GUI

GUI development tools, such as PowerShellStudio, make it very easy to manage events for controls on our winforms.

Once the control is on the form, and we select it, click on the Events button (the lightning symbol), the Properties panel gives us a list of the events available for us to manage. However, events are not just restricted to controls. There’s a world of other events out there that we can use to interact with our winforms projects.

In this article, we’ll create a forms project that downloads the latest 64 bit antimalware definitions from Microsoft and updates a progress control to show how far the download is to completion, using methods and events from a .NET class.

Updates to the latest antimalware definitions can be obtained through http://go.microsoft.com/fwlink/?LinkID=87341&clcid=0x409 and a look through MSDN shows us that we can use the .NET WebClient class to carry out downloads programmatically.

To start this process, create a new forms project, and drag a progress bar, label, and button onto the form. Then set the properties of the controls as below. Note that properties with text controls will automatically be named for you if you set the text property first.

Label
Text : Progress
Name : labelProgress

Button
Text : Download
Name : buttonDownload

Progress Bar
Name : progressbarDownload

Here’s how my form looks.

Blog - Adding Events - Form Design

Once this is complete, we can begin writing the event code.

In our forms Load event, we create an instance of the System.Net.Webclient class. This is assigned to the script level variable, $webclient. This scope is required in order for the other parts of the solution to be able to process the object and its events.

The next two lines add event handlers for the DownloadProgressChanged and DownloadFileCompleted events. DownloadProgressChanged indicates a change in the state of the transfer with regards to the amount of content downloaded, whilst DownloadFileCompleted is fired on the completion of a download. The scriptblocks for these are $webclient_DownloadProgressChanged and $webclient_DownloadFileCompleted respectively.

The event handler for updating the progress of the download is written next:

To make it easier to read, $progressInfo is used for the rest of the code instead of $_. The variable contains the values given to us by the System.Net.DownloadProgressChangedEventArgs class instance that is passed into the handler.

The DownloadProgressChangedEventArgs class contains ProgressPercentage, BytesReceived, and TotalBytesToReceive properties. We use these for changing the progress meter value property, and also updating the text in the label below to show bytes received and the total size of the download.

The event handler for DownLoadFileCompleted is next:

When DownloadFileCompleted is fired, the label text is changed to indicate the download’s completion.

Lastly, the download button’s Click event is set to begin an asynchronous download of the antimalware definition.

Blog - Adding Events - Code

Our project code

And when we run the project and click on Download! We see this in action, with the progress bar being updated and the progress text below it also, using the code we wrote earlier.

Blog - Adding Events - Downloader Running

The downloader in action

This same methodology can be employed for using .NET events, creating an instance of the object, adding the event handler definition, and then the scriptblock code to be used.

You can find exported project code and the project files at my repository on GitHub, and a short video of the project in action on the powershell.amsterdam YouTube channel.

 

Removing Items from Lists Using the Keyboard

In an earlier post, we created a form with two listgridview controls, and used both add and remove buttons, and double click functionality to allow an item to move an item from one control to another in an intuitive manner.

Todays post shows how we can use a remove items from a list by pressing a key. Specifically, we’ll be using the DELETE key for removing items. This will be carried out in Sapien’s PowerShell Studio 2015, but the same methodology applies to however you generate winforms in PowerShell.

For initial setup, carry out the following :

  • create a new form with a header and several items.
  • create a listview control called $lstControl
  • populate the control with a header
  • add some items to the listview control

Sample form and control layout

 

  • select the control
  • select Events in the properties pane
  • double click on KeyDown
  • Insert the following code :

The KeyDown event’s code

 

Go ahead and test it, adding an item to the control on the right hand side, selecting it, and then pressing the DELETE key.

Also, because the code loops through each selected item in the control, we can also use standard multiple selection functionality offered by the various use of the SHIFT and CTRL combinations.

Two items are selected using a click SHIFT combination

The DELETe key is pressed, and the previous selected items are removed from the list

You can find the files, if you are using PowerShell Studio 2015, or exported .ps1 file at my gitlab repository.

Additionally, there’s a (basic) video of this code in action at my channel on You Tube.

Thanks for reading, and feel free to provide feedback.

cheers,

Tim

Using Double Click for Adding and Removing Items from Lists

Double click functionality for movement of items between listboxes is commonly used within Windows, and quite intuitive. This article shows how we can implement this in our own forms based projects. We’ll use this example with ListView, but it is also applicable to ListBoxes (ListView controls inherit from ListBoxes).

For initial setup of this project, follow the steps below, using your preferred GUI editor or code.

  • Create a new forms project
  • Change the form’s control name and text if desired (called AddServers and Double Click Demo in this article)
  • Add two ListView controls, with names of lstFrom, and lstTo
  • Add two Button controls, with names of btnAdd, and btnRemove
  • (optional) Set the Text property of the form

lstFrom

  • Add a column to the form
    • Name : columnComputernameFrom
    • Sorting : Ascending
    • Text : Computername
    • View : Details
    • Add the following items to lstFrom , with Text values of Computer1, Computer2, Computer3, and Computer4

lstTo

  • Add a column to the form
    • Name : columnComputernameFrom
    • Text : Computername
    • View : Details
    • Sorting : Ascending

Buttons
Set the name of the top button to btnAdd, and the Text property to >
Set the name of the bottom button to btnRemove, and the Text property to <

Arrange the controls to look something like the picture below :

Our form design

Our form design

Once this is complete, we’re going to start adding some features.

Add/Remove Buttons

This could be described as the ‘classic’ method of adding and removing items from lists, with arrows pointing in alternative directions to indicate the addition or removal of an item from one listbox to another.

In the Load event, we’ll set the arrow buttons Enabled property to $false, since no items are selected.

Let’s activate or deactive the add and remove buttons depending on whether the appropriate listboxes are populated, and additionally disable the appropriate button when an item is selected. There’s no point of the add button being enabled when we have selected an item from the To listgridview for example.

Now we add the code for the button events, adding to removing from the appropriate listgridview. We use the FindItemWithText method to verify that the item does not already exist there, preventing duplications.

Now go ahead and run it. Select double click on an item on the left hand column, and it will add it to the right one, and versa.

Double Click - Running 1

Double click on one of the items

Double Click - Running 2

…..and it is moved to the other side

 

The mechanisms that double click provides for list also be used on other controls. For example, double clicking on an item in a list which automatically populates a textbox with the value that has been selected in the list.

You can find a copy of the PowerShell Studio .psf form file, and also an exported .ps1 of the same for at my repository on GitHub.

A video of this is also available on the PowerShell.Amsterdam YouTube channel.

Thanks for reading, and please provide feedback if you have comments, questions, or have noticed any errors in this article.

cheers,

Tim