Visual Basic 5-6 Course Part 7

19

Click here to load reader

Transcript of Visual Basic 5-6 Course Part 7

Page 1: Visual Basic 5-6 Course Part 7

Visual Basic 5 Programming - 7 A Specialised Training Course

Page 2: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 1

Contents

EXCHANGING DATA BETWEEN APPLICATIONS .................................................................................... 2

IMPORT / EXPORT OF FILE FORMATS ...................................................................................................... 2

CLIPBOARD ........................................................................................................................................................ 2

CLEAR METHOD ............................................................................................................................................... 3

GETFORMAT METHOD ..................................................................................................................................... 3

GETTEXT METHOD ........................................................................................................................................... 3

SETTEXT METHOD............................................................................................................................................ 3

GETDATA METHOD .......................................................................................................................................... 4

SETDATA METHOD ........................................................................................................................................... 4

COMBINING THE METHODS ............................................................................................................................... 4

CONTROLLING OTHER APPLICATIONS.................................................................................................... 4

SHELL FUNCTION.............................................................................................................................................. 4

ACTIVATING AN APPLICATION ALREADY RUNNING ........................................................................................... 5

SENDING KEYSTROKES TO ANOTHER APPLICATION........................................................................................... 5

OLE - OBJECT LINKING AND EMBEDDING .............................................................................................. 6

OBJECT LINKING OR EMBEDDING? ................................................................................................................... 6

OLE Object............................................................................................................................................... 6

Linked Data.............................................................................................................................................. 6

Embedded Data........................................................................................................................................ 6

USING THE OLE CONTROL ............................................................................................................................... 6

Adding the OLE Control to your application ........................................................................................... 7

Create New option.................................................................................................................................... 7

Create from File option............................................................................................................................ 7

Sizing the Object....................................................................................................................................... 8

OLE Control Pop-up menus ..................................................................................................................... 8

MANIPULATING PROPERTIES AT RUN-TIME .................................................................................................... 10

Class property ........................................................................................................................................ 10

OLEType & OLETypeAllowed properties .............................................................................................. 10

SourceDoc property ............................................................................................................................... 10

SourceItem property ............................................................................................................................... 10

Action property....................................................................................................................................... 11

UpdateOptions property......................................................................................................................... 12

AutoActivate property ............................................................................................................................ 12

USING OLE VERBS......................................................................................................................................... 12

AutoVerbMenu property......................................................................................................................... 12

Is that it? ................................................................................................................................................ 12

APPENDIX.......................................................................................................................................................... 13

SENDKEYS STRING SYNTAX............................................................................................................................ 13

EXERCISES........................................................................................................................................................ 15

EXERCISE 2 .................................................................................................................................................... 17

Page 3: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 2

Exchanging Data between applications Back in the good old days of stand alone DOS applications, exchanging data between them

was simple, not necessarily easy to perform, but conceptually simple. Applications could

Import and Export data to and from certain file types but no dynamic updating of shared data

was generally possible.

Since Windows has been on the scene we have seen a steady development of more complex,

dynamic methods of linking. The stage we have reached so far in Windows is a selection

between...

• Import / Export of file formats

• Cutting, copying and pasting of text and graphics (Clipboard)

• Messaging between active applications (DDE or sending keystrokes)

• Embedding or Linking of Objects (OLE2 but now called ActiveX)

The technology involved is by no means limited to Windows, but as we are interested in

Visual Basic 5 we shall ignore the wider view. Although DDE or Dynamic Data Exchange

is still supported, it is becoming obsolete in industry and as such will not be covered in this

course.

Import / Export of File Formats The traditional approach may appear redundant, but many people are re-implementing

existing systems and need access to existing data file formats. Unless there are specific

Custom Controls for these file formats (there is a wide range of 3rd Party controls available)

you will need to understand the file format's construct and write your own file handling

routines to read or write a file of that format. Many Windows applications have import filters

for older file formats and could be used as a go-between.

Clipboard Most of you will have used the Clipboard in Windows at some time or other, perhaps without

realising it.

The Clipboard is effectively built into Windows and can be accessed by any application for

storing text or graphic data that has been cut or copied from an application until it is pasted

somewhere.

As mentioned earlier in the course the Clipboard is a system object with a set of methods.

• Clipboard.Clear

• Clipboard.GetFormat

• Clipboard.GetText

• Clipboard.GetData

• Clipboard.SetText

• Clipboard.SetData

Page 4: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 3

Clear Method

This simply clears the data in the Clipboard. Be aware that setting any other text or graphic

data into the Clipboard automatically replaces the existing contents.

GetFormat Method

The Clipboard can hold two general kinds of data, text and graphics. There are however

several graphic formats available. The following table shows each type...

Symbolic constant Value Clipboard format

vbCFLink &HBF00 DDE conversation information

vbCFText 1 Text

vbCFBitmap 2 Bitmap (.BMP files)

vbCFMetafile 3 Metafile (.WMF files)

vbCFDIB 8 Device-independent bitmap

vbCFPalatte 9 Colour palette

vbCFEMetafile 14 Enhanced Metafile (.EMF files)

vbCFFiles 15 File list from Windows Explorer

The GetFormat method is used in the following syntax...

x% = Clipboard.GetFormat( argument )

The argument specifies one of the following Clipboard formats recognised by Visual Basic as

shown in the table and can be either the value or Symbolic Constant. The method returns

True if there is an item on the Clipboard that matches the specified format. Otherwise, it

returns False.

GetText method

This enables you to retrieve a text string stored in the Clipboard and assign it to a variable or

property. It recognises the vbCFText and vbCFLink formats (see above), but mostly we will

need to obtain text data.

The syntax is...

dest = Clipboard.GetText(format)

where dest is the string that is assigned the string contents of the Clipboard and format is one

of the two valid formats. If you leave out the format then vbCFText is assumed.

SetText method

This method places text into the Clipboard in one of the two text formats. The syntax is...

Clipboard.SetText data [,format]

Data can be any string, a literal, either a variable or a string returned from an expression.

For example...

Clipboard.SetText Text1.SelText

copies the selected text in a textbox into the Clipboard.

Page 5: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 4

GetData method

This method returns a picture which can be assigned to a suitable control property such as a

PictureBox picture property. A specific format can be retrieved, omitting the format or setting

the format to 0 (zero) automatically sets the format.

dest = Clipboard.GetData()

SetData method

Finally we have a method for placing a graphic on the Clipboard. Again the format can be

omitted or set to 0 (zero) which will allow the system to set the format.

Clipboard.SetData data [, format]

Combining the methods

Be aware that most controls such as the TextBox include support for shortcut key cutting

copying and pasting of text. You will only need to resort to the methods when implementing

menu events or control events that cut, copy or paste.

Controlling other applications Before we discuss OLE/ActiveX , we shall look at...

• Launching other applications

• Activating applications already running

• Sending Keystrokes to other applications

Shell Function

This function allows you to launch an application (including those that run under DOS) in

Windows.

Use the following syntax...

Shell(commandstring [, windowstyle])

The commandstring is the name of the program to execute and any required arguments or

command line switches. If the program name in commandstring doesn't include a .COM, .EXE,

.BAT, or .PIF file extension, .EXE is assumed. Unless a full path is specified, Shell will search

in the Windows and Windows\System directory and any directories on the path.

Page 6: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 5

Constant Value Window style

vbHide 0 Hidden.

vbNormalFocus 1 Normal size and position with focus.

vbMinimizedFocus 2 Minimised with focus (default).

vbMaximisedFocus 3 Maximised with focus.

vbNormalNoFocus 4 Restored to most recent size without focus

vbMinimizedNoFocus 6 Displayed as an icon, without focus

The windowstyle is a number corresponding to the style of the window in which the program

is to be executed. (If windowstyle is omitted, the program is opened minimised with focus,

the same as windowstyle = 2).

The Shell function runs other programs asynchronously. That means that you cannot depend

on a program started with Shell to be finished executing before the code following the Shell

function in your Visual Basic application is executed.

Activating an application already running

Shelling another application can cause problems when an instance of that application is

already running. In that case we can simply activate the existing instance.

AppActivate title

The argument titletext is a string expression that is the name that appears in the title bar of the

application window to activate. If there is more than one instance of the application, the

operating environment arbitrarily selects the one to activate. The name that appears in the title

bar and titletext must match character-for-character, but the comparison is not case sensitive:

"Calculator" and "calculator" appear identical.

The AppActivate statement changes the focus to the named application window but does not

affect whether it is maximised or minimised. Focus moves from the activated application

window when the user takes some action to change the focus or close the window.

Sending Keystrokes to another application

Windows maintains an event message queue for all messages for all current applications.

What Visual Basic does is add keystrokes to the queue but address them to another

application making it appear to the other application that the user is entering keystrokes from

the keyboard.

Sendkeys string

The keystrokes are destined for the current application (the one with focus) but are not

actually sent until VB5 yields control to the other application, i.e. when your VB5 application

is idle.

Alternatively you can cause the keystrokes to be sent immediately by including True at the

end of the command...

Sendkeys string, True

See APPENDIX for syntax of strings.

Page 7: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 6

OLE - Object Linking and Embedding OLE permits Windows applications to work together to create compound documents. A

compound document is the result of two or more applications contributing to a single

application. For example a Word for Windows document may include a spreadsheet produced

by Excel as well as MS-Chart, MS-Drawing, or WordArt applet objects and even multimedia

animations and sounds.

With OLE 2.0, as well as including the data from a server application the client document can

include OLE automation. With OLE automation the client can instruct the server to perform

various actions on the OLE objects.

Object Linking or Embedding?

Perhaps a better description as an OLE object is either Linked or Embedded.

OLE Object

This is the unit of data belonging to a different application included as part of a compound

document. An application that receives and displays an object is a container application. For

example, a Visual Basic application that uses an OLE control to embed or link data from

another application is a container application.

Linked Data

Is physically stored and maintained by the server application. The container establishes a link

to the data by a reference. If the container document is transferred to another system the

linked data files need to be moved too.

Embedded Data

Is physically stored in the container document but maintains a reference to the server

application that created the data enabling it to be called upon to edit the embedded object.

When the whole document is transferred to a new system, embedded objects are transferred

as part of it.

Using the OLE Control

When included the following icon appears in your toolbox....

Page 8: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 7

Adding the OLE Control to your application

As you place an instance of the OLE Control on your form a box with sizing handles appear

together with the following Insertable Objects Dialog Box...

This lists all the applications and utilities in the present Windows environment that can

produce OLE objects.

Create New option

Create New allows you to invoke the server application to create an embedded object of the

type selected from the list box when OK is clicked.

Create from File option

Selecting Create from File replaces the list box with a text box and Browse button that

allows you to select a file of any type. The Link CheckBox determines whether the object is

linked or embedded.

Page 9: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 8

Sizing the Object

Once the OLE control has been linked with the OK button, or no link established and the

control left by clicking the Cancel button, it can be resized using the handles. At run-time the

size can of course be adjusted using the relevant properties.

OLE Control Pop-up menus

At run-time and at design time pop-up menus are available for manipulating the object and

they are launched by right clicking the object and selecting edit...

Pop-up for object at design-time

In both instances a Microsoft Chart applet object has been embedded into an OLE control on

a form. The run-time menu shows only the entries below the separator.

The Menu options are as follows...

Option Description

Insert Object Allows you to insert a new object in the control, opens the Insert

Object dialog box

Paste Special If a suitable set of data is stored in the Clipboard this is enabled

allowing you to paste the object into the control

Delete Embedded Object Clears the link when embedded

Delete Linked Object Clears the link when linked

Page 10: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 9

Create Link Activated when the SourceDoc property is set.

Create Embedded Object Activated when the Class or SourceDoc property is set.

Below Separator or

Runtime options

These reflect the Verbs that the object supports such as Edit or

Play (media)

Page 11: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 10

Manipulating properties at Run-Time

The type of object does not need to be determined at design time. At run time various

properties can be manipulated that effect the control contents.

Class property

An objects class determines the application that provides the objects data and the type of data

the object contains. The class names of some commonly used Microsoft applications include

MSGraph, MSDraw, WordDocument, and ExcelWorksheet. (You can get a list of the class

names available to your application at design-time by selecting the Class property in the

Properties window and clicking on the three dots in the Settings box.)

Note The Insert Object dialog does not display a list of class names. This dialog displays

user-friendly names for each class of object, which are generally longer and more easily

understood.

OLEType & OLETypeAllowed properties

OLEType determines whether the control can allow ...

• linking (0, vbOLELinked)

• embedding (1, vbOLEEmbedded)

• none (3, vbOLENone).

OLETypeAllowed indicates which is current...

• both (2, vbOLEEither - default).

SourceDoc property

This specifies the name of the particular server document that becomes an OLE object.

oleName.SourceDoc [ = filename ]

Use the SourceDoc property to specify the file to be linked when creating a link. Use the

SourceItem property to specify data within the file to be linked.

When creating an embedded object, if the SourceDoc property is set to a valid file name, an

embedded object is created using the specified file as a template.

SourceItem property

For linked objects this property specifies the range of data which becomes linked.

oleName.SourceItem [ = stringexpression ]

Each object uses its own syntax to describe units of data. To set this property, specify a unit

of data recognized by the object. For example, when you link to Microsoft Excel, you specify

the SourceItem using a cell or cell-range reference such as "R1C1" or "R3C4:R9C22," or a

named range such as "Revenues."

Page 12: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 11

Action property

This specifies the operation that the OLE control should perform.

oleName.Action = setting

By setting the Action property at run time, you can perform the following operations...

Setting Description

0 CreateEmbed creates an embedded object.

To use this action, you must first set the Class and OleTypeAllowed properties.

correctly. The Class property determines the type of OLE object to create.

1 CreateLink creates a linked OLE object from the contents of a file.

To use this action, you must first set the OleTypeAllowed and SourceDoc

properties correctly. The SourceDoc property specifies the file from which the

OLE object is created. You can also set the SourceItem property.

4 Copy copies the object to the Clipboard.

5 Paste copies data from the Clipboard to an OLE control.

6 Update retrieves the current data from the application that supplied the object and

displays that data as a picture in the OLE control.

7 DoVerb opens an OLE object for an operation, such as editing.

9 Close closes an embedded OLE object

10 Delete deletes or removes the OLE object

11 SaveToFile must be preceded by opening a Binary file, the FileNumber property

must be set accordingly.

12 ReadFromFile uses binary files as above

14 InsertObjDlg displays the Insert Object Dialog box

15 PasteSpecialDlg displays the Paste Special dialog

17 FetchVerbs Updates the list of Verbs supported in popup menu

18 SaveToOle1File relates to earlier versions

Page 13: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 12

UpdateOptions property

Determines how an object is updated when linked data is modified.

olename.UpdateOptions [ = option ]

The UpdateOptions property settings are:

Setting Description

0 (Default) Automatic. The object is updated each time the linked data

changes. vbOLEAutomatic

1 Frozen. The object is updated whenever the user saves the linked document

from within the application in which it was created. vbOLEFrozen

2 Manual. The object is updated only when the Action property is set to 6

(Update). vbOLEManual

AutoActivate property

Allows the user to activate an object by double-clicking the OLE control, or by giving the

OLE control the focus.

oleName.AutoActivate = [setting ]

Setting Description

0 vbOLEActivateManual. The OLE object is not automatically activated. You

can activate an object programmatically by setting Action = 7 (DoVerb).

1 vbOLEActivateGetFocus. If the OLE control contains an object, the

application that provided the object will be activated when the OLE control

gets the focus.

2

(Default)

vbOLEActivateDoubleclick. If the OLE control contains an object, the

application that provided the object will be activated when the user double-

clicks the control.

When vbOLEActivateAuto is set to this the DblClick event is blocked.

Using OLE Verbs

The server application determines what actions that can occur when an OLE object is

activated. The set of actions available are defined as Verbs.

Activation can occur either by

• using the pop-up menu and selecting from the Verb list

• setting the Action property to DoVerb with the verb property set

AutoVerbMenu property

The pop-up menu can be disabled by setting the AutoVerbMenu property to False.

Is that it?

No - you could run a whole course on all the issues relating to OLE2. What we have covered

here are the basics to enable you to utilise OLE2 in your applications. Once happy with these

concepts you should look at the manual to go further.

Page 14: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 13

APPENDIX

SendKeys string syntax

Each key is represented by one or more characters. To specify a single keyboard character,

use the character itself. For example, to represent the letter A, use "A" for keytext. If you

want to represent more than one character, append each additional character to the one

preceding it. To represent the letters A, B, and C, use "ABC" for keytext.

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses ( ) have special

meanings to SendKeys. To specify one of these characters, enclose it inside braces. For

example, to specify the plus sign, use {+}. Brackets ([ ]) have no special meaning to

SendKeys, but you must enclose them in braces as well, because in other applications for

Microsoft Windows, brackets do have special meaning that may be significant when dynamic

data exchange (DDE) occurs. To send brace characters, use {{} and {}}.

To specify characters that aren't displayed when you press a key (such as Enter or Tab) and

keys that represent actions rather than characters, use the codes shown below...

Key Code Key Code

Backspace {BACKSPACE} or {BS}

or {BKSP}

Break {BREAK}

Caps Lock {CAPSLOCK} Clear {CLEAR}

Del {DELETE} or {DEL} Down Arrow {DOWN}

End {END} Enter {ENTER} or ~

Esc {ESCAPE} or {ESC} Help {HELP}

Home {HOME} Ins {INSERT}

Left Arrow {LEFT} Num Lock {NUMLOCK}

Page Down {PGDN} Page Up {PGUP}

Print Screen {PRTSC} Right Arrow {RIGHT}

Scroll Lock {SCROLLLOCK} Tab {TAB}

Up Arrow {UP} F1 {F1}

F2 {F2} F3 {F3}

F4 {F4} F5 {F5}

F6 {F6} F7 {F7}

F8 {F8} F9 {F9}

F10 {F10} F11 {F11}

F12 {F12} F13 {F13}

F14 {F14} F15 {F15}

F16 {F16}

Page 15: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 14

To specify keys combined with any combination of Shift, Ctrl, and Alt keys, precede the

regular key code with one or more of the following codes...

Key Code

Shift +

Control ^

Alt %

To specify that Shift, Ctrl, and/or Alt should be held down while several other keys are

pressed, enclose the keys' code in parentheses. For example, to have the Shift key held down

while E and C are pressed, use "+(EC)". To have Shift held down while E is pressed,

followed by C being pressed without Shift, use "+EC". To specify repeating keys, use the

form {key number}; you must put a space between key and number. For example, {LEFT 42}

means press the Left Arrow key 42 times; {h 10} means press h 10 times.

Page 16: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 15

Exercises

Preparation

For this set of exercises you will need project directories for the following projects...

• ClipType

• RunNote

Exercise 1

In this exercise you will develop a utility that mainly sits on your desktop informing you what

type of data is currently in the clipboard.

1 Start a new project. Place a timer control on your form. Set the following properties...

Control Type Name Property Setting

Form frmMain Caption

WindowState

Icon

Clipview

1 - minimised

E:\Program files\DevStudio\VB\ Setupkit\Setup1\Setup1.ICO

(drive depends on network mapping on server)

Timer Timer1 Interval 1000 *

* - The timer interval property determines how long between Timer events and is

measured in milliseconds, this one will activate every second.

2 Create a menu bar with the following options...

Menu Level Caption Name

Top &Quit mnuQuit

“ &Clear mnuClear

Page 17: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 16

3 Develop the following event procedures...

Sub Form_Load ()

Timer1.Interval = 1000

Me.Height = 600

Me.WindowState = 1

End Sub

Sub mnuClear_Click ()

Clipboard.Clear

End Sub

Sub mnuQuit_Click ()

End

End Sub

Sub Timer1_Timer ()

Dim CType As String

Dim NewType As Integer

If Clipboard.GetFormat(&HBF00) Then

CType = "[DDE Stuff]"

NewType = &HBF00

ElseIf Clipboard.GetFormat(1) Then

CType = "[Text]"

NewType = 1

ElseIf Clipboard.GetFormat(2) Then

CType = "[Bitmap]"

NewType = 2

ElseIf Clipboard.GetFormat(3) Then

CType = "[MetaFile]"

NewType = 3

ElseIf Clipboard.GetFormat(8) Then

CType = "[DIB]"

NewType = 8

ElseIf Clipboard.GetFormat(9) Then

CType = "[Palette]"

NewType = 9

Else

CType = "[empty]"

NewType = 0

End If

4 Save the form and project as MAIN.FRM and CLIPTYPE.VBP

Make your project into an .EXE file.

5 Run your application on the desktop. Run other applications (e.g. Notepad,

Paintbrush) so that you can place various formats in the Clipboard, check that the

caption changes to reflect this by assigning CType to the forms caption.

6 Would a select case instead of the compound if then statements work? Instead of

using numbers, use the equivalent constants. Which do you think is easier to

understand when reading the code?

Page 18: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 17

Exercise 2

In this exercise we shall use Shell to control a few accessory apps.

1) Set up a form with the following controls and properties, and save as AppL

Control Name Properties

Form frmAppStart Caption =

“ApplicationLauncher”

Command Button cmdCalc Caption = “Calculator”

Command Button cmdCal Caption = “Calendar”

Command Button cmdNote Caption = “NotePad”

Option Button optStyle(0) Caption = “Run app as

normal window”

Option Button optStyle(1) Caption = “Run app as

minimised window”

Option Button optStyle(2) Caption = “Run app as

maximised window”

Label lblDisplay Caption = “Application: “

( position just above buttons )

CheckBox chkSend Caption = “Send

Keystrokes?”

2) Type in the following code in the General/Declarations

Option Explicit

Dim app As Double

Dim winstyle As Integer

Dim cap As String

3) Then add the event procedure code:

Private Sub cmdCal_Click()

app = Shell("c:\windows\calendar.exe", winstyle)

End Sub

Page 19: Visual Basic 5-6 Course Part 7

Visual Basic Book 7 © Mark Collins 1999 Page 18

Private Sub cmdCalc_Click()

Dim i As Integer

app = Shell("c:\windows\calc.exe",winstyle)

If chkSend.Value = 1 Then

For i = 1 To 100

SendKeys i & "{+}", True

Next i

SendKeys "=", True

End If

End Sub

Private Sub cmdNote_Click()

App = Shell("c:\windows\notepad.exe",winstyle)

If chkSend.Value = 1 Then

SendKeys " This is a test string, man! ", True

End If

End Sub

Private Sub Form_Load()

optStyle(0).Value = True

winstyle = 1

End Sub

Private Sub optStyle_Click(Index As Integer)

winstyle = Index + 1

End Sub

Why do you think that when you run the calendar program there is an error? Hint Windows

NT has security/permissions for running programs.