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!


Asynchronously Save Images in the Clipboard to File

PowerShell v5.0 introduces us with two cmdlets, Get-Clipboard and Set-Clipboard which, just as their names suggest, allow us to obtain and set the contents of the clipboard. What’s not immediately apparent though is that these cmdlets can process more than just text in the clipboard.

In this blog, we’ll focus on using Get-Clipboard, and create a script which is used in combination with Register-EvengineEvent to save an image to file any time that one is detected in the clipboard during the current session. A repo containing the script is available at GitHub

Get-Clipboard supports the processing of several types of data that is in the clipboard, one of which is that of an image type. Examples of these would be print screens or copying an image created in Paint into the clipboard.

When an image is in the clipboard, and we use Get-Clipboard -Format Image, an object of Bitmap type (inherited from System.Drawing.Image) is returned. One of the methods this class provides is Save. Save has several overloads, one of which writes to a file and a variety of formats of your choice.

The script below requires use of the ISE, and uses Register-EngineEvent to register a scriptblock, which runs when a PowerShell.OnIdle event is raised. In the scriptblock, we check to see if there is any content in the clipboard of image type. If there is, we take the details of the current file open in ISE the editor, and use it to generate a unique filename. Then, the content of the clipboard is saved to this filename using the method mentioned above. Finally, we clear the clipboard to ensure that there we don’t end up in a continuous looping operation.

Thanks for reading!


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 :

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 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.

Text : Progress
Name : labelProgress

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 YouTube channel.


Using the MouseEnter and MouseLeave Events in PowerShell Studio

Default Winforms on their own can sometimes look a bit bland, but there are some things we we can do, which do not require much coding, that can really enrich the GUI experience.

The MouseEnter and MouseLeave events can be easily overlooked when writing a forms application. A MouseEnter event is raised when the mouse pointer moves over an area, or to be more correct, a specific controls region. The MouseLeave event is the opposite. It is raised when the pointer is moved outside of the region of a control.

You can take advantage of these events in many ways. In this post, we’ll use them to highlight the control over which the pointer is, and display descriptive text associated with that control. The style is meant to be not unsimilar to some of the Microsoft installation dialogs. 🙂

NB If you wish, you can skip the steps below by downloading the source files from my GitHub repository.

Create the Forms Project

First of all, create a new forms project. Let’s call it MouseEnter. Now add the following controls, setting their properties as mentioned below.

Control Type Name Text BackColor Font
Form frmMouseEnterDemo MouseEnter demo White default
Panel panel1 na 1,36,86 default
Label labelDescription Description na Size 10, Bold
Label LabelOptions Options na Size 10, Bold
Label LabelOverview Overview na default
Label LabelMouseEnterApplication MouseEnter Application na default

Position labelDescription so that it occupies the left half of the form, underneath the blue panel.

Position these last three labels on the right hand side of the form, with the Options label at the top, followed by the other two directly under it.

Your form layout should now look something like this :

MouseOver - Initial Form Setup

With the labelDescription control positioned as we want it, clear its the text property, so that it is blank.

Now we need to add code for five events :

  • form loading
  • mouse enters overview label region
  • mouse leaves overview label region
  • mouse enters mouse enter application region
  • mouse leaves mouse leave application region

Writing the Event Code

We’ll register event handlers for the above actions by the process below, and then paste in the event code that is further down this page.

  • Select the properties panel, and the events (lightening) button
  • Double click on the form
  • Go back to the form view, select the overview label, double click on MouseEnter.
  • Do this also for the MouseLeave event
  • Repeat the above for the mouseenterapplication label.

Once you have completed, this your form should show a set of entries for the events we have selected. These will be empty. Select the text, and clear it.

Select the text below, copy it into the clipboard, and then paste it into the code window.

This sets the text that  to be shown when a control’s region is entered or left by the mouse pointer, and also other actions to be performed in these circumstances. When the pointer enters a control’s region, we set its text is set blue, and the label on the left hand of the screen displays some descriptive text. On startup, or when a pointer leaves a controls region, this description is reset back to the default welcome text.

mouseover - part 2 - form code

Rearrange your form as you wish.


Now let’s run our project to see the results.

Overview - MouseEnter

Overview Mouse Enter

Overview - MouseLeave/Not in any region

Overview MouseLeave

When the pointer is positioned over one of the options, the font changes to blue, and the descriptive text on the left hand side also changes. When the pointer moves outside the controls region, the default text is displayed, and the font set back to black.

And a video which highlights what’s happening a bit better. Apologies for the poor quality, I’m still wrestling with uploads to YouTube at the moment :

As always, comments and feedback welcome. Thanks for reading.