Implementing Drag-and-Drop in Visual Basic 6

Implementing Drag-and-Drop in Visual Basic 6

ne major advantage of the Windows operating system?and most other operating systems for that matter?is that it provides all programs with a similar user interface. A program’s menu, for example, is always displayed across the top of its window, and its commands can be accessed with the mouse or by using the Alt key. Pressing Alt+F4 closes a program, F1 is almost always the Help key, and Ctrl+P usually is the command for printing. These and other cross-program similarities in user interface commands make the user’s life a lot easier. Imagine having to learn a new interface and all new commands for each program!

One important aspect of the Windows interface that many developers overlook is drag-and-drop. The ability to carry out program operations using drag-and-drop can be a significant part of a user interface, particularly for those users who are happier using the mouse rather than the keyboard. Implementing drag-and-drop in a Visual Basic 6 program is a relatively simple task. This article covers only traditional drag-and-drop, which permits items to be dragged from one part of a program to another part of the same program. There is a second kind of drag-and-drop that permits items to be dragged from one program to another program, which is not covered here.

The Basics of Drag and Drop
A drag-and-drop operation involves a source and a target. The source can be any Visual Basic control, and the target can be any control or the form itself. The operation has three parts:

  • The operation begins when the user presses the mouse button as the pointer is over a control that has been enabled as a drag-and-drop source.
  • The operation continues as the pointer is moved, with the left mouse button still down, over other controls or the form itself. A control receives notification, via the DragOver event, that it is being “dragged over” and can signal whether the data can be dropped on it by changing the appearance of the mouse pointer.
  • The operation ends when the user releases the mouse button. A control is notified by the DragDrop event that it has been dropped on.

It’s important to note that what is being dragged is the source control. It’s not being dragged literally?it does not move on the form?but its identity is being dragged. Both the DragOver and DragDrop events inform the target control of the identity of the source control, and code in the event procedure can take action accordingly.Controls have two properties that are related to drag-and-drop:

  • DragMode. Set to vbManual (value = 0, the default) for manual drag-and-drop, which requires use of the Drag method to initiate a drag-and-drop operation. The control can act as a drag-and-drop source only if you put the required code in the MouseDown event procedure to begin the operation. Set to vbAutomatic (value = 1) to have drag-and-drop initiated automatically when the user depresses the mouse on the control.
  • DragIcon. Specifies the mouse pointer that is displayed while the control is being dragged. The default setting displays an arrow with a rectangle. For a custom mouse icon, set this property at design-time to a .ICO or .CUR file, or at run-time use the LoadPicture function to load an .ICO file.

Executing the Drag method on the source control is required only when the its DragMode property is set to vbManual. The syntax for this method is:

object.Drag action 

Set action to vbBeginDrag (value = 1) to initiate a drag operation. This will usually be done in the source control’s MouseDown event procedure. You can also call the Drag method with action set to vbCancel or vbEndDrag (values 0 and 2 respectively) to cancel an ongoing drag-and-drop operation or to end a drag-and-drop operation.

Controls have two events that are related to drag-and-drop. DragOver is used to detect when an object is dragged over a control, and DragDrop is used to detect when an object is dropped on a control:

target_DragOver(source As Control, x As Single, y As Single, State As Integer) target_DragDrop(source As Control, x As Single, y As Single) 

Target identifies the target object (the one being dragged over or dropped on). It can be a form, an MDI form, or a control. If the target is a control that is part of a control array, these event procedures will have an additional argument that specifies the Index property of the control within the control array.

Source identifies the source control (where the drag-drop operation began).

X and y give the horizontal and vertical position of the mouse pointer with respect to object. These values are always expressed according to the object’s coordinate system.

State specifies the relationship between the mouse pointer and the target, as follows:

  • A value of 0 indicates the pointer just entered the target.
  • A value of 1 indicates the pointer is leaving the target.
  • A value of 2 indicates that the pointer is moving within the target.

When a source control is dragged and dropped, here’s what happens:

  1. When the mouse pointer leaves the source control, the parent form receives a single DragOver event with the State argument equal to 0.
  2. As the pointer moves over the form the form receives multiple DragOver events with the State argument equal to 2.
  3. When the source is dragged over another control on the form, the form receives a DragOver event with the State argument equal to 1 (signaling that the pointer has left the form), and the control over which the source was just dragged receives a DragOver event with the State argument equal to 0 (signaling that the pointer has entered the Form).
  4. When the control is dropped, the object it is currently over receives a DragDrop event.

Let’s look at some examples, starting with something really simple. Create a Visual Basic project and place a Text Box and a Label on the form. Set the Text Box’s DragMode property to vbAutomatic. Put the following code in the Label’s DragDrop event procedure:

Private Sub Label1_DragDrop(Source As Control, _    X As Single, Y As Single) Label1.Caption = Source.Text End Sub 

When you run the project, enter some text in the Text Box then drag from the Text Box to the Label. Doing this, you’ll see that the text is copied from the Text Box to the Label.

Now add some enhancements. Suppose you do not want the drag operation to be possible if the Text Box is empty. Change the Text Box’s DragMode property back to the default setting of vbManual. Then, add this code to the Text Box’s MouseDown event procedure:

Private Sub Text1_MouseDown(Button As Integer, _    Shift As Integer, X As Single, Y As Single) If Len(Text1.Text) > 0 And Button = 1 Then    Text1.Drag vbBeginDragEnd If End Sub

The If statement checks to see if the Text Box contains text and also makes sure that the left mouse button is depressed, as is traditional for drag-and-drop operations. Only if both conditions are met is a drag-drop operation started.In the previous example, the mouse cursor displayed its default dragging cursor while the Text Box was being dragged?the normal arrow plus a rectangle the same size as the source control. There was no indication of where the Text Box could be dropped (such as the Label control) or where it could not be dropped (the form). Change the code so the drag icon indicates whether or not a drop is possible as the cursor moves around the form. To do this, use an icon editor to create two icons, one a red circle with a slash through it named NO.ICO and the other a green checkmark called YES.ICO. Place both icon files in the Visual Basic project folder.

The first step is to modify the DragIcon property of the Text Box to NO.ICO. This means that the default icon displayed during dragging will be the “no” icon unless it is explicitly modified. Next, write code to change the icon to YES.ICO when the cursor is dragged over the Label control, and to change it back to NO.ICO when and if the cursor leaves the Label control and re-enters to Form. Here’s the required code:

Private Sub Label1_DragOver(Source As Control, _    X As Single, Y As Single, State As Integer)   If Source.Name = "Text1" And State = 0 Then      Text1.DragIcon = LoadPicture(App.Path & "yes.ico")  End If End Sub Private Sub Form_DragOver(Source As Control, _    X As Single, Y As Single, State As Integer)   If Source.Name = "Text1" And State = 0 Then      Text1.DragIcon = LoadPicture(App.Path & "
o.ico")  End If End Sub 

 
Figure 1 | Click here to get a close-up view of the cursor displaying the “no” icon.

Now, the cursor displays the “no” symbol, as shown in Figure 1, when dragging over the form. Only when the cursor is over the Label control does the cursor display the “yes” icon (Figure 2).

 
Figure 2 | Click here to get a close-up view of the cursor displaying the “yes” icon.

Sometimes your drag-drop code will be interested in the type of the source rather than in its specific identify. For example, the demonstration program could be modified to contain multiple Text Box controls, and you want to enable drag-and-drop from any of them to the Label control. Then you can use the TypeOf operator to determine the type of the source control. For example:

If TypeOf Source Is TextBox Then....End If

You can modify the demo program with some additional textBox controls. Make the following code modifications so that the proper icon is displayed and the drop operation is performed regardless of which Text Box is the source.

You can modify the demo program with some additional textBox cointrols. Make the following code modifications so that the proper icon is displayed and the drop operation is performed regardless of which Text Box is the source.

Private Sub Form_DragOver(Source As Control, _    X As Single, Y As Single, State As Integer)  If TypeOf Source Is TextBox Then      Text1.DragIcon = LoadPicture(App.Path & "
o.ico")  End IfEnd SubPrivate Sub Label1_DragDrop(Source As Control, _    X As Single, Y As Single)  If TypeOf Source Is TextBox And State = 0 Then    Label1.Caption = Source.Text  End SubPrivate Sub Label1_DragOver(Source As Control, _    X As Single, Y As Single, State As Integer)  If TypeOf Source Is TextBox And State = 0 Then      Text1.DragIcon = LoadPicture(App.Path & "yes.ico")  End IfEnd Sub

This demonstration project is available for download as the project DragDrop. It makes a good starting point for your own experiments with Visual Basic drag-and-drop.

devx-admin

devx-admin

Share the Post:
Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1