You are on page 1of 270

TM

TM

LabWindows /CVI Basics II


Course Manual

Course Software Version 8.0


March 2006 Edition
Part Number 321057G-01
LabWindows/CVI Basics II Course Manual
Copyright
19962006 National Instruments Corporation. All rights reserved.
Under the copyright laws, this publication may not be reproduced or transmitted in any form, electronic or mechanical, including
photocopying, recording, storing in an information retrieval system, or translating, in whole or in part, without the prior written consent
of National Instruments Corporation.
National Instruments respects the intellectual property of others, and we ask our users to do the same. NI software is protected by
copyright and other intellectual property laws. Where NI software may be used to reproduce software or other materials belonging to
others, you may use NI software only to reproduce materials that you may reproduce in accordance with the terms of any applicable
license or other legal restriction.
Trademarks
National Instruments, NI, ni.com, and LabVIEW are trademarks of National Instruments Corporation. Refer to the Terms of Use section
on ni.com/legal for more information about National Instruments trademarks.
Tektronix and Tek are registered trademarks of Tektronix, Inc. Other product and company names mentioned herein are trademarks
or trade names of their respective companies.
Members of the National Instruments Alliance Partner Program are business entities independent from National Instruments and have
no agency, partnership, or joint-venture relationship with National Instruments.
Patents
For patents covering National Instruments products, refer to the appropriate location: HelpPatents in your software,
the patents.txt file on your CD, or ni.com/legal/patents.

Worldwide Technical Support and Product Information


ni.com
National Instruments Corporate Headquarters
11500 North Mopac Expressway Austin, Texas 78759-3504 USA Tel: 512 683 0100
Worldwide Offices
Australia 1800 300 800, Austria 43 0 662 45 79 90 0, Belgium 32 0 2 757 00 20, Brazil 55 11 3262 3599, Canada 800 433 3488,
China 86 21 6555 7838, Czech Republic 420 224 235 774, Denmark 45 45 76 26 00, Finland 385 0 9 725 725 11,
France 33 0 1 48 14 24 24, Germany 49 0 89 741 31 30, India 91 80 41190000, Israel 972 0 3 6393737, Italy 39 02 413091,
Japan 81 3 5472 2970, Korea 82 02 3451 3400, Lebanon 961 0 1 33 28 28, Malaysia 1800 887710, Mexico 01 800 010 0793,
Netherlands 31 0 348 433 466, New Zealand 0800 553 322, Norway 47 0 66 90 76 60, Poland 48 22 3390150,
Portugal 351 210 311 210, Russia 7 095 783 68 51, Singapore 1800 226 5886, Slovenia 386 3 425 4200,
South Africa 27 0 11 805 8197, Spain 34 91 640 0085, Sweden 46 0 8 587 895 00, Switzerland 41 56 200 51 51,
Taiwan 886 02 2377 2222, Thailand 662 278 6777, United Kingdom 44 0 1635 523545
For further support information, refer to the Additional Information and Resources appendix. To comment on National Instruments
documentation, refer to the National Instruments Web site at ni.com/info and enter the info code feedback.

Contents
Student Guide
A.
B.
C.
D.
E.
F.

LabWindows/CVI Training and Certification Sequence......................................vii


Course Description ...............................................................................................vii
What You Need to Get Started .............................................................................viii
Installing the Course Software..............................................................................ix
Course Goals.........................................................................................................ix
Course Conventions ..............................................................................................x

Lesson 1
Review of Basics I Concepts
Introduction.................................................................................................................1-1
The Callback Function Model ....................................................................................1-2
Introduction to Messaging ..........................................................................................1-3
Messaging ...................................................................................................................1-4
Structure of Instrument Drivers ..................................................................................1-5
Accessing Instrument Drivers.....................................................................................1-6
Toolslib Instrument Drivers........................................................................................1-7
Summary Lesson 1......................................................................................................1-8

Lesson 2
User Interface Programming
Introduction.................................................................................................................2-1
Lesson 2 Project..........................................................................................................2-2
Exercise 2-1
User Interface Project .......................................................................2-4
Attributes ....................................................................................................................2-5
Exercise 2-2
Search ...............................................................................................2-7
Menus..........................................................................................................................2-11
Menu Editor ................................................................................................................2-12
Menu Callback Functions ...........................................................................................2-14
Menus: Programming Method ....................................................................................2-15
Exercise 2-3
Menus ...............................................................................................2-17
Canvas Control ...........................................................................................................2-24
Graphs versus Canvases..............................................................................................2-25
Using a Canvas ...........................................................................................................2-26
Useful Type Definitions for Canvases........................................................................2-27
Useful Functions for Canvases ...................................................................................2-28
Canvas Functions ........................................................................................................2-29
Exercise 2-4
Canvas Controls................................................................................2-31
Table Control ..............................................................................................................2-36
Table Control Components .........................................................................................2-37
Programming with the Table Control .........................................................................2-38
Exercise 2-5
Table Controls ..................................................................................2-41

National Instruments Corporation

iii

LabWindows/CVI Basics II Course Manual

Contents

Tree Control ................................................................................................................2-47


Exercise 2-6
Tree Controls ....................................................................................2-50
Intensity Graphs ..........................................................................................................2-56
Intensity GraphsPlotIntensity Function ..................................................................2-57
Intensity GraphsColor Map Array ..........................................................................2-59
Exercise 2-7
Intensity Graph Controls ..................................................................2-61
User-Defined Custom Controls ..................................................................................2-64
Predefined Custom Controls .......................................................................................2-65
Predefined Custom ControlsPath Control...............................................................2-66
Predefined Custom ControlsPassword Control ......................................................2-67
Predefined Custom ControlsCombo Box ...............................................................2-68
Predefined Custom ControlsFile Browser ..............................................................2-69
Exercise 2-8
Predefined Custom Controls.............................................................2-71
Predefined Custom ControlsToolbar ......................................................................2-73
Predefined Custom ControlsToolbar Functions .....................................................2-74
Exercise 2-9
Toolbars............................................................................................2-77
Predefined Custom ControlsOther Controls ...........................................................2-81
Summary Lesson 2......................................................................................................2-82

Lesson 3
Interapplication Communication and ActiveX Automation
Introduction.................................................................................................................3-1
ActiveX Technologies ................................................................................................3-2
Client-Server Relationship..........................................................................................3-3
Type Library ...............................................................................................................3-4
ActiveX Automation Client-Server Architecture .......................................................3-5
ActiveX Features in LabWindows/CVI......................................................................3-6
LabWindows/CVI as ActiveX Container ...................................................................3-7
LabWindows/CVI as Automation Client....................................................................3-8
LabWindows/CVI as Automation Server ...................................................................3-9
Exercise 3-1
Using ActiveX Objects.....................................................................3-11
ActiveX Automation...................................................................................................3-13
LabWindows/CVI as an Automation Client ...............................................................3-14
Creating Automation Clients ......................................................................................3-15
LabWindows/CVI ActiveX Controller Wizard ..........................................................3-16
Wizard-Generated Functions ......................................................................................3-17
ActiveX Functions ......................................................................................................3-17
Automation Data Types ..............................................................................................3-18
Other ActiveX Library Functions ...............................................................................3-19
Exercise 3-2
Using an ActiveX Server..................................................................3-21
Exercise 3-3
Creating an ActiveX Client Application ..........................................3-28
LabWindows/CVI as an Automation Server ..............................................................3-35
Creating ActiveX Servers ...........................................................................................3-36
Editing ActiveX Servers .............................................................................................3-37
Exercise 3-4
Running an ActiveX Server..............................................................3-39
DataSocket Technology ..............................................................................................3-40
LabWindows/CVI Basics II Course Manual

iv

ni.com

Contents

DataSocket Features ...................................................................................................3-41


Data Entities and Attributes ........................................................................................3-42
DataSocket API...........................................................................................................3-43
Structure of a Data Writer...........................................................................................3-44
Structure of a Data Reader..........................................................................................3-45
Exercise 3-5
Creating DataSocket Writer and Reader Applications.....................3-47
DataSocket Binding ....................................................................................................3-51
Exercise 3-6
Using DataSocket Binding ...............................................................3-53
Using LabVIEW (Optional)........................................................................................3-56
Exercise 3-7
Using the CVI Function Panel Converter (Optional) .......................3-58
Controlling VIs from LabWindows/CVI Using VI Server (Optional) .......................3-61
Exercise 3-8
Communicating with LabVIEW VIs (Optional) ..............................3-63
Transmission Control Protocol (Optional) .................................................................3-68
TCP Client-Server Architecture..................................................................................3-69
TCP Servers and Clients .............................................................................................3-70
TCP Callback Functions .............................................................................................3-71
TCP Server/Client Functions ......................................................................................3-72
ServerTCPRead/ClientTCPRead ................................................................................3-73
Exercise 3-9
Examining a TCP Application in LabWindows/CVI.......................3-75
Summary Lesson 3......................................................................................................3-78

Lesson 4
Code Modularity and Compatibility
Introduction.................................................................................................................4-1
Modules ......................................................................................................................4-2
Dynamic Link Library (DLL).....................................................................................4-4
Creating DLLs ............................................................................................................4-6
Calling Conventions ...................................................................................................4-7
Using DLLs.................................................................................................................4-8
Exercise 4-1
Creating a DLL in LabWindows/CVI ..............................................4-10
Exercise 4-2
Using a DLL Created in LabWindows/CVI.....................................4-15
Debugging DLL Code ................................................................................................4-16
Exercise 4-3
Examining DLL Debugging Features ..............................................4-19
DLL Recommendations ..............................................................................................4-21
Compatibility with External Compilers ......................................................................4-22
Using LabWindows/CVI Libraries in External Compilers.........................................4-23
Other Issues with External Compilers ........................................................................4-27
Using the User Interface Library with External Compilers ........................................4-30
Exercise 4-4
Creating an Object File for Use in an
External Compiler (Optional)...........................................................4-33
Exercise 4-5
Creating a DLL for Use in an External Compiler (Optional)...........4-37
Summary Lesson 4......................................................................................................4-39

National Instruments Corporation

LabWindows/CVI Basics II Course Manual

Contents

Lesson 5
Additional Topics
Introduction.................................................................................................................5-1
Multithreading Terms .................................................................................................5-2
Multithreaded Programs .............................................................................................5-3
Benefits of Multithreading..........................................................................................5-4
Multithreading in LabWindows/CVI..........................................................................5-5
Thread Pools ...............................................................................................................5-6
Thread Pool Example..................................................................................................5-7
Exercise 5-1
Multithreading in LabWindows/CVI ...............................................5-10
Thread Safe Queues ....................................................................................................5-12
Thread Safe Queue Example ......................................................................................5-13
Exercise 5-2
Using a Thread Safe Queue..............................................................5-15
Well-Behaved Applications ........................................................................................5-24
Platform Software Development Kit (SDK)...............................................................5-25
Benefits of Using SDK Functions ..............................................................................5-26
Additional Functions...................................................................................................5-27
I/O and Memory Space ...............................................................................................5-28
Memory Display Window ..........................................................................................5-29
Source Code Browser .................................................................................................5-30
Handling Executables in LabWindows/CVI...............................................................5-31
Error Handling ............................................................................................................5-32
Set Sleep Policy ..........................................................................................................5-33
Additional Functionality .............................................................................................5-34
Toolkits .......................................................................................................................5-35
Summary Lesson 5......................................................................................................5-38
LabWindows/CVI Publications ..................................................................................5-39
Continuing with National Instruments........................................................................5-40

Appendix A
Additional Information and Resources
Course Evaluation

LabWindows/CVI Basics II Course Manual

vi

ni.com

Student Guide
Thank you for purchasing the LabWindows/CVI Basics II course kit.
This course manual and the accompanying software are used in the two-day,
hands-on LabWindows/CVI Basics II course.
You can apply the full purchase price of this course kit toward the
corresponding course registration fee if you register within 90 days of
purchasing the kit. Visit ni.com/training to register for a course and to
access course schedules, syllabi, and training center location information.

A. LabWindows/CVI Training and Certification Sequence


The LabWindows/CVI Basics II course is part of a series of courses and
certifications designed to build your proficiency with LabWindows/CVI and
to distinguish your expertise with industry-recognized credentials.
Hands-on training courses shorten learning curves and the NI Certified
LabWindows/CVI Developer (CCVID) certification distinguishes an
advanced level technical expertise in using LabWindows/CVI to develop
comprehensive solutions. The following illustration shows the courses and
exams that are part of the LabWindows/CVI training and certification series.
Refer to ni.com/training for more information about NI Certification.

Certification Track

LabWindows CVI
Experience

LabWindows CVI
Basics I

LabWindows CVI
Basics II

Certified LabWindows
CVI Developer Exam

Instrument Driver
Development

B. Course Description
The LabWindows/CVI Basics II course is a follow-up to the
LabWindows/CVI Basics I course. This course is ideal for new and
intermediate users. After attending the course, you can design powerful
multithreaded applications that use Internet communication, DLLs, and
ActiveX. You will learn how to create powerful user interfaces using active
menus, canvas controls, and toolbars. You will be able to take full advantage
of the PC with your application by learning how to program a multithreaded
application. This course assumes that you have completed
LabWindows/CVI Basics I course or you are familiar with the
LabWindows/CVI environment and possess basic C programming skills.

National Instruments Corporation

vii

LabWindows/CVI Basics II Course Manual

Student Guide

The course is divided into lessons, each covering a topic or a set of topics.
Each lesson consists of the following parts:

An introduction that describes what you will learn.

A discussion of the topics.

A set of exercises that reinforces the topics presented in the discussion.


Some lessons include optional exercises or challenge steps to complete
if time permits.

A summary that outlines important concepts and skills taught in the


lesson.

C. What You Need to Get Started


Before you use this course manual, make sure you have the following items:
Windows 2000 or later installed on your computer. The course is
optimized for Windows XP.
GPIB interface.
A GPIB cable.
NI Instrument Simulator and power supply.
LabWindows/CVI Full Development System 8.0 or later.
LabWindows/CVI Basics II CD, which contains the following files:
Filename

Description

Exercises

Folder containing the exercises used in the


course and for saving LabWindows/CVI files
created during the course

Solutions

Folder containing the solutions to all the


course exercises

LabWindows/CVI Basics II Course Manual

viii

ni.com

Student Guide

D. Installing the Course Software


Complete the following steps to install the course software.
1. Insert the course CD in your computer. The CVI Basics Course Material
Setup dialog box displays.
2. Click Next.
3. Click Next to begin the installation.
4. Click the Finish to exit the Setup Wizard.
5. The installer places the Exercises and Solutions folders at the top
level of the C: directory.
The exercise files are located in the C:\Exercises\CVI Basics II
directory and the solution files are located in the C:\Solutions\CVI
Basics II directory.

Repairing or Removing Course Material


You can remove the course material using the Add or Remove Programs
feature on the Windows Control Panel. Remove the course material if you
no longer need the files on your machine.

E. Course Goals
This course presents the following topics:

Create user interfaces with toolbars and menus.

Use ActiveX within the LabWindows/CVI environment.

Compile modules as DLLs so they can be used with other applications.

Use LabWindows/CVI to access DLLs.

Develop efficient multithreaded applications.

Develop applications that can communicate with the Internet.

Decrease development time using debugging features.

This course does not include following topics:

Every built-in function or library. Refer to the NI LabWindows/CVI Help


for more information about LabWindows/CVI features not described in
this course

Detailed explanation of ActiveX technology

Detailed explanation of TCP/IP protocol

Operation of the GPIB bus

Developing a customized application for any student in the class.

National Instruments Corporation

ix

LabWindows/CVI Basics II Course Manual

Student Guide

F. Course Conventions
The following conventions are used in this course manual:
<>

Angle brackets that contain numbers separated by an ellipsis represent a


range of values associated with a bit or signal namefor example,
AO <3..0>.

[]

Square brackets enclose optional itemsfor example, [response].

The symbol leads you through nested menu items and dialog box options
to a final action. The sequence FilePage SetupOptions directs you to pull
down the File menu, select the Page Setup item, and select Options from
the last dialog box.
This icon denotes a tip, which alerts you to advisory information.
This icon denotes a note, which alerts you to important information.

bold

Bold text denotes items that you must select or click in the software, such as
menu items and dialog box options. Bold text also denotes parameter names,
buttons on the User Interface (*.uir), and sections and components of
dialog boxes. Window names and palette names are also denoted in bold.

italic

Italic text denotes variables, emphasis, a cross-reference, or an introduction


to a key concept. Italic text also denotes text that is a placeholder for a word
or value that you must supply.

monospace

Text in this font denotes text or characters that you enter from the keyboard,
sections of code, programming examples, and syntax examples. This font
also is used for the proper names of disk drives, paths, directories, programs,
subprograms, subroutines, device names, functions, operations, variables,
filenames, and extensions.

monospace bold

Bold text in this font denotes the messages and responses that the computer
automatically prints to the screen. This font also emphasizes lines of code
that are different from the other examples.

monospace
italic

Italic text in this font denotes text that is a placeholder for a word or value
that you must supply.

LabWindows/CVI Basics II Course Manual

ni.com

Review of Basics I Concepts


Lesson 1: Review of Basics I Concepts
A. Callback function model
B. Software instrument drivers
.fp files
Source options
C. Toolslib
Useful instrument drivers

Introduction
In this lesson, you will learn about the concepts that are the foundation for building
LabWindows/CVI programs.

National Instruments Corporation

1-1

LabWindows/CVI Basics II Course Manual

Lesson 1

Review of Basics I Concepts

The Callback Function Model


The LabWindows/CVI programming model relies
heavily on callback functions
Callback function gives the user or system a way to
communicate with your code
Callback function are called when event occurs
All relevant data is passed when callback functions
are called
The Callback Function Model
LabWindows/CVI libraries make extensive use of callback functions. A LabWindows/CVI library
calls a callback function in response to an internal condition or event, such as a mouse click. Your
application code generally does not call these functions, though this is certainly possible. Instead,
the callback functions give the user or system a way to communicate with your code. In terms of
your application, you write the callback function and wait for LabWindows/CVI to call it.
Typically, the callback function is passed a parameter containing information about the specific
condition that occurred and one or more additional parameters further describing the condition.
The prime example of a callback function is a user interface panel or control callback. When events
occur on the user interface, these functions are called and pass all data relevant to the events.
LabWindows/CVI uses the callback function mechanism throughout many of the core libraries and
instrument drivers.
With this LabWindows/CVI user interface callback function model, you can build powerful,
event-driven graphical user interfaces (GUIs) quickly and easily.

LabWindows/CVI Basics II Course Manual

1-2

ni.com

Lesson 1

Review of Basics I Concepts

Introduction to Messaging
A message queue is set up when the operating
system starts your application
As events occur, the operating system stores
different messages in the queue
Your application continuously checks the queue to
take action on the various messages

Introduction to Messaging
When discussing the general callback function mechanism internal structure, it is necessary to look
at the concept of operating system messaging. A common construct in modern operating systems
(Windows 2000/NT/9x included), a messaging scheme offers applications a consistent and
straightforward way to respond to modern graphical user interfaces and other types of actions.
In addition to other services provided to every application, the operating system (OS) manages a
message queue for the application. When the OS detects events such as a mouse movement, it
places well-defined messages in this queue. An application loops and polls to check for messages
in the queue. If messages exist, the application removes the messages and takes appropriate action.
In a LabWindows/CVI application, think of ProcessSystemEvents as the function that checks
the queue and takes appropriate action. As discussed in LabWindows/CVI Basics I,
RunUserInterface manages the core looping of your application and relies on the functionality
of ProcessSystemEvents.
ProcessSystemEvents examines the new message and determines how to handle it. In the case
of a user interface action, ProcessSystemEvents determines the appropriate control and calls

its callback function.

National Instruments Corporation

1-3

LabWindows/CVI Basics II Course Manual

Lesson 1

Review of Basics I Concepts

Messaging
ProcessSystemEvents
CVICALLBACK function ()
switch(event)
{
case EVENT_LEFT_CLICK:

Left-mouse down

break;

Left-mouse up

case EVENT_COMMIT:
break;
}

Message queue

Messaging
The figure above illustrates the general message processing scheme. Consider the following
example:
A LabWindows/CVI application with a simple one-button panel is running. When the user
clicks and releases the left mouse button, the OS queues the appropriate messages.
ProcessSystemEvents, whether you call it directly or call it through RunUserInterface,
detects these messages and extracts them from the queue. Upon examining the messages,
ProcessSystemEvents determines that the user clicked and released the button on the
application. First, the function sends an EVENT_LEFT_CLICK to your buttons callback function.
Then, when that call returns, ProcessSystemEvents calls the function again with the
EVENT_COMMIT. ProcessSystemEvents does the message-handling work for you. For this
reason, it is important that you understand the callback function mechanism because you must
always first check the event passed into the function and determine what action to take. The
switch-case C language structure is the best way to do this.
Note User interface callback functions typically return 0. If the function returns a
nonzero number, any subsequent callbacks resulting from that particular event are not
called. This process is known as swallowing the event.

LabWindows/CVI Basics II Course Manual

1-4

ni.com

Lesson 1

Review of Basics I Concepts

Structure of Instrument Drivers


Library function prototypes
.h header file

Library function definitions


.fp file
.c, .lib, or .dll file containing code

Structure of Instrument Drivers


In preparation for the next lessons, you will briefly review instrument drivers as simple software
components. Recall that a .fp file does not contain any code. Rather, the .fp file provides a user
interface for function panels, help for the .fp file, the hierarchy of the function panels, and the
names and signatures of all functions in the library.
LabWindows/CVI loads a .fp file and searches for a corresponding header and source module.
The corresponding header and source modules have the same base name as the .fp file.
LabWindows/CVI loads the code and header file much as if you had added them to the project
yourself. When you run the function panel interactively, LabWindows/CVI executes the code in the
corresponding module. This code module can be actual source code, an object file, or a static or
dynamic link library.
An instrument driver can contain code used to accomplish any taskthe task does
not need to be related to actual hardware communication.
Note

National Instruments Corporation

1-5

LabWindows/CVI Basics II Course Manual

Lesson 1

Review of Basics I Concepts

Accessing Instrument Drivers


Add the .fp file to the Library menu
Add the .fp file to the Library Tree
Load the .fp file through the Instrument menu
Add the .fp file to your project
Auto-load the .fp file from another instrument
driver

Accessing Instrument Drivers


You can use instrument drivers in your application in several ways.

Add the .fp file to the LabWindows/CVI Library menu. In the Workspace window, select
LibraryCustomize to add libraries.

Add the .fp file to the Instruments folder of the Library Tree. Right-click the Instruments
folder and select Load Instrument.

Load the .fp file through the Instrument menu.

Add the .fp file to your project. Doing so causes LabWindows/CVI to load the instrument each
time it loads your project file.

Auto-load the .fp file from another instrument driver. You can auto-load a .fp file when you
have an instrument driver that relies on code in an external library. Rather than compiling that
library into your own instrument driver or forcing the instrument driver user also to load the
support library, you can configure one instrument driver to auto-load another. To configure
auto-loading, select InstrumentEdit, which opens the Edit Instrument dialog box. Click Edit
Function Tree to open the Function Tree Editor. Then select Edit.FP Auto-Load List and
list the .fp files for the instrument drivers you want to load when the current instrument driver
is loaded. The instrument driver from which to auto-load the .fp files must be loaded to
complete these steps.

Because the .fp file does not contain any code, you can add only the source and header
modules to your project and use them as if they were not associated with an instrument driver
at all. In this case, you lose the benefits of the function panels.

LabWindows/CVI Basics II Course Manual

1-6

ni.com

Lesson 1

Review of Basics I Concepts

Toolslib Instrument Drivers


The toolslib folder of your LabWindows/CVI
installation contains many useful, extended libraries
Instrument drivers are a great way to encapsulate
custom user interface controlstoolslib
contains several custom controls

Toolslib Instrument Drivers


LabWindows/CVI provides a Tools Library that contains additional instrument drivers to
accomplish common tasks. You can find these libraries in the toolslib folder located in
C:\Program Files\National Instruments\CVI. For example, the inifile instrument
driver offers a set of functions to manage configuration information in hierarchical .ini files.
While browsing through the LabWindows/CVI core libraries, take some time to examine these
instrument drivers.

National Instruments Corporation

1-7

LabWindows/CVI Basics II Course Manual

Lesson 1

Review of Basics I Concepts

Summary Lesson 1
Lesson 1 reviews and extends core LabWindows/CVI
concepts from the Basics I course.
Callback function programming model
Instrument drivers as user libraries
Toolslib instrument drivers

Summary Lesson 1
This lesson describes key programming concepts with the LabWindows/CVI libraries. Lesson 2
gives you hands-on experience developing programs with toolslib instrument drivers to
implement advanced user interface features.

LabWindows/CVI Basics II Course Manual

1-8

ni.com

Lesson 1

Review of Basics I Concepts

Notes

National Instruments Corporation

1-9

LabWindows/CVI Basics II Course Manual

Lesson 1

Review of Basics I Concepts

Notes

LabWindows/CVI Basics II Course Manual

1-10

ni.com

User Interface Programming


Lesson 2: User Interface Programming
A.
B.
C.
D.
E.
F.
G.
H.

Attributes
Menus
Intensity graphs
Canvases
Table controls
Tree controls
Custom controls
Toolbars

Introduction
With LabWindows/CVI user interface functions and features, you can build powerful, event-driven
GUIs quickly.
As you develop LabWindows/CVI applications, you add user interface controls to panels, edit their
properties, and then create the corresponding callback functions to handle user events that are
generated by operations on those controls.
You can enhance your applications with advanced user interface controls, custom controls, and
built-in user interface features that increase usability and flexibility for the end user.
This lesson focuses on user interface programming style and taking advantage of your own user
interface elements.

National Instruments Corporation

2-1

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Project

Lesson 2 Project
In this lesson, you will create a project that uses several LabWindows/CVI user interface (UI)
features. The project integrates menus, toolbars, canvas controls, multiple panels, intensity graphs,
table controls, and tree controls. You add each feature one at a time, so that you can see how each
benefits the overall application.
The final section in this lesson covers many of the custom control instrument drivers that ship with
LabWindows/CVI.

LabWindows/CVI Basics II Course Manual

2-2

ni.com

Lesson 2

User Interface Programming

Exercise 2-1

OBJECTIVE

Time to complete: 5 min.

To run the application that you create


To explore the functionality of the application

National Instruments Corporation

2-3

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Exercise 2-1
Objective:

User Interface Project

To run the project you will create.


Before you start building the project in Lesson 2, run the application to see
the various features that are included.

1. Run the uiproject.exe executable located in the directory


C:\Exercises\CVI Basics II\Lesson 2\execs.
2. Examine the features you will add throughout Lesson 2.

Menus

Intensity graphs

Canvas controls

Table controls

Tree controls

Toolbars

3. Click the Quit button when you finish studying the application.

End of Exercise 2-1

LabWindows/CVI Basics II Course Manual

2-4

ni.com

Lesson 2

User Interface Programming

Attributes
All user interface objects have attributes such as color, visibility,
position, or size.
For example, this STOP button has the following attributes:
Color:

Red

Visibility: True
GetCtrlAttribute and SetCtrlAttribute retrieve and set control attribute
values.

Attributes
In LabWindows/CVI, every UI object has attributes such as color, visibility, position, and size.
Some objects have specific attributes. For example, a graph has attributes for grid lines and its
X and Y axes. You can set the attributes of objects in the User Interface Editor. You also can set the
attributes programmatically. Use the User Interface Library GetCtrlAttribute and
SetCtrlAttribute functions to change the appearance and functionality of UI objects.

National Instruments Corporation

2-5

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Exercise 2-2

OBJECTIVE

Time to complete: 20 min.

To add search capabilities to an application

LabWindows/CVI Basics II Course Manual

2-6

ni.com

Lesson 2

Exercise 2-2
Objective:

User Interface Programming

Search

To add search capabilities to a LabWindows/CVI application.


In this exercise, you will add search functionality to the application to allow
the user to search for a string entered in the Find text control. After the
application finds the string, the application highlights the appropriate text in
the text box control. If the application does not find the string, the
application displays a message stating that the string does not exist.

Examine the following code for the SearchRoutine function that you will
create in this exercise. Complete the steps following the code to use
LabWindows/CVI to quickly develop the code for the SearchRoutine
function.

National Instruments Corporation

2-7

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

1. Load the uiproject.prj file located in the directory


C:\Exercises\CVI Basics II\Lesson 2\uiproject.prj.

Open uiproject.c. The code is partially completed for you.


2. Place your cursor inside the SearchRoutine function, which already
is declared.
3. Use the FindPattern function to search the contents of the text box
for the search string stored in the buffer FindThis.
Press the <Ctrl-Shift-P> key to find a function panel. You can use this technique
whenever you need a function panel.
Tip

Alternatively, you can also find the FindPattern function panel by


selecting Formatting and I/O LibraryString Manipulation
FindPattern from the Library Tree. Complete the function panel as
shown in the following table.
Buffer

Buffer

Starting Index

searchposition

Number of Bytes

Pattern

FindThis

Case Sensitive?

No

Start From Right?

No

Result

result

LabWindows/CVI Basics II Course Manual

2-8

ni.com

Lesson 2

User Interface Programming

4. Select CodeInsert Function Call. The input parameters already


are declared. FindPattern searches Buffer starting at
searchposition for the pattern stored in FindThis.
5. Declare the variable result in the function SearchRoutine. Use the
value of result to determine if the search string exists. If the string
exists, highlight the text in the text box.
Tip You can declare the variable result from the FindPattern function panel by
pressing <Ctrl-D> in the Result control.

6. Insert an If-Else statement to test if a result was found from the search
string. FindPattern returns 1 if the string is not found. Select Edit
Insert ConstructIf Else. In the If Else dialog box, enter
result >= 0 for the condition. Click OK to insert the construct.
7. FindPattern uses searchposition to determine where to start
searching for a particular text string. In order for FindPattern to
find multiple instances of the same search string, it is necessary to set
the value of searchposition equal to one character after the
FindPattern result. This allows FindPattern to search for the text
string after the current search instance. Enter the following code in the
if statement:
searchposition = result + 1;

8. If the search string is found, the code located in the if statement


executes. In the if statement, highlight the found text. Use
SetCtrlAttribute to highlight the text. You must call the
SetCtrlAttribute function twice. The first function call defines the
start position where the highlighting begins. The second function call
defines the length of the highlighted text.
a. From the Library Tree, select User Interface Library
Controls/Graphs/Strip ChartsGeneral Functions
SetCtrlAttribute and complete the function panel for the first
function call as shown in the following table. After you finish, select
CodeInsert Function Call.
Panel Handle

mainPanel

Control ID

MAINPANEL_TEXTBOX

Control Attribute

Text Selection Start

Attribute Value

result

b. Insert the second SetCtrlAttribute function call as shown in the


following table. You must calculate the length of the string to
highlight. Use the ANSI C strlen function to calculate the length.

National Instruments Corporation

2-9

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Panel Handle

mainPanel

Control ID

MAINPANEL_TEXTBOX

Control Attribute

Text Selection Length

Attribute Value

strlen(FindThis)

9. Use SetActiveCtrl to make the text box the active control so that the
user can see the highlighted text. From the Library Tree, select User
Interface LibraryControls/Graphs/Strip ChartsGeneral
FunctionsSetActiveCtrl and complete the function panel for the
function call, as shown in the following table. After you finish, select
CodeInsert Function Call.
Panel Handle

mainPanel

Control ID

MAINPANEL_TEXTBOX

10. In the else statement, call MessagePopup to display a message that


the search string was not found. From the Library Tree, select User
Interface LibraryPop-up PanelsMessage/Prompt Popups
MessagePopup and complete the function panel as shown in the
following table to display a meaningful error message. After you finish,
select CodeInsert Function Call.
Title

String Not Found

Message

The Search String Was


Not Found

11. FindPattern uses searchposition to determine where to start


searching for a particular text string. In cases in which the user inserts a
new string for the search after the error message, FindPattern should
search the entire text from the beginning. This is possible if
searchposition points to the first character in the text. To add this
functionality to your program, enter the following code after the
MessagePopup statement:
searchposition = 0;

12. Save and run the project. Test the application to confirm that the search
function works properly and highlights the appropriate string in the text
box when the search string is found.

End of Exercise 2-2

LabWindows/CVI Basics II Course Manual

2-10

ni.com

Lesson 2

User Interface Programming

Menus
Create menus in the User Interface Editor
You must load a menu onto a panel
Menus have callbacks similar to controls and panels
Menu
Menu
Item

Menu Bar
Submenu

Menus
In LabWindows/CVI Basics I, you learned how to create GUIs. Now, you will learn how to add
pull-down menus to your panels so that your program looks and feels like a modern application.
Menus are primarily for user input. You do not display information in a menu as you do in a
numeric indicator.
The following list describes important menu terms:

Menu barA menu bar is the entire menu associated with a panel. For example, the Source
window in LabWindows/CVI has a menu bar consisting of File, Edit, View, Build, and so on.

MenuA menu is one element of the menu bar. File is one menu, Edit is another.

Menu itemA menu item is an element from the pull-down menu. Open is an item of the File
menu.

SubmenuA submenu is a menu displayed by selecting a menu item.

Immediate Action MenuAn immediate action menu is a menu that has no menu items
placed beneath it. An exclamation point appears next to the immediate action menu name.

National Instruments Corporation

2-11

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Menu Editor

Menu bar prefix combined with constant name creates the MENU_FILE
Control ID
Name that
appears in menu

Menu Editor
You can program and identify menu bars and panels in a similar way. Remember that a panel has
a constant name. The Control ID of any control placed on that panel consists of this panel constant
name followed by the controls own constant name. For example, PNL_GRAPH is the Control ID of
a graph that has the constant name GRAPH and is placed on a panel that has the constant name PNL.
You use this Control ID when you need to refer to a specific control programmatically.
Menu bars also have constant names, and any menu or menu item placed on the menu bar inherits
that name. For example, if you add a File menu with the constant name FILE to a menu bar with
the constant name MENU, the File menu ID is MENU_FILE. If you add an Open menu item with the
constant name OPEN under the File menu, the Open menu item ID is MENU_FILE_OPEN. To create
menus in the User Interface Editor, select CreateMenu Bar.
Menu Editor Terms

Menu Bar Constant PrefixThe constant name associated with a menu bar. This prefix is
similar to the constant name given to a panel.

Constant NameThe unique name that identifies a menu or menu item on the menu bar. This
name is similar to the constant name given to a control on a panel.

Item NameThe text shown in the menu bar such as File, Edit, and so on. You can use this
text for a pull-down menu or a menu item.

Callback FunctionThe name of the function that executes when you select the menu item.

Modifier Key and Shortcut KeyThe hot key combination accesses the menu item. Using
this combination is equivalent to using the mouse to select the menu item.

LabWindows/CVI Basics II Course Manual

2-12

ni.com

Lesson 2

User Interface Programming

The buttons on the right-hand side of the menu editor position the menu item in the menu hierarchy.
You can move a menu item up, down, right, or left in the menu hierarchy. For example, to create a
File menu with Open and Exit as two menu items, place File in the menu hierarchy and insert the
Open and Exit menu items into the menu. Then highlight the Open item and click the right-hand
Change Level button to position the Open item as a child item of File. Repeat this process with
the Exit menu item. You also can insert items below an item by clicking the Insert Child Item
button.

National Instruments Corporation

2-13

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Menu Callback Functions


Menu callbacks have the following form:
void CVICallback CallbackFunction-name(int
menuBar, int menuItem,
void *callbackData, int panel);

Menu callbacks work like control callbacks, except there is


no event parameter in menu callbacks
Any idea why?

Menu Callback Functions


Callback functions respond in the same way when a user selects a menu item or clicks a button.
The major difference between control callback functions and menu callback functions is that there
is no event parameter to check in menu callbacks. This is because multiple events cannot occur on
a menu item. Only the EVENT_COMMIT event applies to menu callback functions. When your code
enters a menu callback, you know immediately that the user selected the menu item associated with
the callback.
The prototype for menu callbacks is
void CVICallback CallbackFunction-name (int menuBar, int menuItem, void
*callbackData, int panel);

menuBarThe handle of the menu bar that contains the item. Handles are returned from the
LoadMenuBar function. This is similar to LoadPanel.

menuItemThe specific control ID of the item selected. If several menu items use the same
callback function, use this parameter to determine which menu item was selected.

callbackDataA pointer to user-defined data.

panelThe panel handle of the panel displaying the menu.

LabWindows/CVI Basics II Course Manual

2-14

ni.com

Lesson 2

User Interface Programming

Menus: Programming Method


Loading menu bars
LoadMenuBar function
Panel settings in User Interface Editor

Creating menus programmatically


New/DiscardMenu
New/DiscardMenuItem
Set/GetMenuBarAttribute

Menus: Programming Method


You can create menu bars in LabWindows/CVI using the Edit Menu Bar dialog box or
programmatically using the User Interface Library functions.
1. Before you can use a menu in your application, you must load it on the top of the panel. You
can do this by selecting a menu bar from within the Panel Settings section of the Edit Panel
dialog box in the User Interface Editor.
The prototype for LoadMenuBar is
int LoadMenuBar (int destinationPanelHandle, char filename[], int
menuBarResourceID);

This function returns a handle to the menu bar that is used in subsequent calls to menu functions.

destinationPanelHandleThe handle returned by LoadPanel, NewPanel, or


DuplicatePanel that indicates the panel on which the menu bar appears.

filenameThe absolute or relative pathname for the .uir file that contains the menu bar
resource.

menuBarResourceIDThe defined constant assigned to the menu bar in the User Interface
Editor.

2. You can create menus and menu bars programmatically using NewMenuBar, NewMenu, and
NewMenuItem. You also can retrieve and change the attributes of a menu bar, such as font
style, with the GetMenuBarAttribute and SetMenuBarAttribute functions.

National Instruments Corporation

2-15

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Exercise 2-3

OBJECTIVE

Time to complete: 20 min.

To add menus to a LabWindows/CVI application

LabWindows/CVI Basics II Course Manual

2-16

ni.com

Lesson 2

Exercise 2-3
Objective:

User Interface Programming

Menus

To add menus to a LabWindows/CVI application.


In this exercise, you will add a menu to the application. This exercise
illustrates the use of menu callback functions and the ease of adding menus
to an application.
1. Open the uiproject.uir file located in the directory
C:\Exercises\CVI Basics II\Lesson 2\uiproject.uir and
select CreateMenu Bar to display the Edit Menu Bar dialog box, as
shown in the following figure.

2. Use this dialog box to create the menu bar. To add entries to the menu,
fill in the list boxes.
a. Create the File menu with the following entries.

National Instruments Corporation

Menu Bar Constant Prefix

MENU

Constant Name

FILE

2-17

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Item Name

File

Callback Function

Leave blank

b. Click the Insert Child Item button to create the Open menu item
under the File menu. Use the following entries in the Edit Menu Bar
dialog box.
Menu Bar Constant Prefix

MENU

Constant Name

OPEN

Item Name

Open

Callback Function

OpenText

Modifier Key

MenuKey (Ctrl)

Shortcut Key

c. Click the Insert Item button to create the Save menu with the
following entries.
Menu Bar Constant Prefix

MENU

Constant Name

SAVE

Item Name

Save

Callback Function

SaveText

Modifier Key

MenuKey (Ctrl)

Shortcut Key

d. Click the Insert Item button to create the Exit menu item with the
following entries.

LabWindows/CVI Basics II Course Manual

Menu Bar Constant Prefix

MENU

Constant Name

EXIT

Item Name

Exit

Callback Function

ExitProgram

Modifier Key

None

Shortcut Key

No Shortcut Key

2-18

ni.com

Lesson 2

User Interface Programming

e. Click the Insert Item button to create the Search menu with the
following entries.
Menu Bar Constant Prefix

MENU

Constant Name

SEARCH

Item Name

Search

Callback Function

Leave Blank

Modifier Key

None

Shortcut Key

No Shortcut Key

Click the <<Change Level button so the Search menu is not


indented under the File menu.
f. Click the Insert Item button to create the Find menu item with the
following entries.
Menu Bar Constant Prefix

MENU

Constant Name

FIND

Item Name

Find

Callback Function

FindString

Modifier Key

None

Shortcut Key

No Shortcut Key

Click the Change Level>> button so the Find item is indented


under the Search menu. Select MenuKey (Ctrl) for the Modifier
Key and F for the Shortcut Key.
You cannot select modifier and shortcut keys for top level menu items. Therefore,
you must change the Search menu item level before you set the menu items modifier
and shortcut keys.
Note

g. Click the Insert Item button to create the Case Sensitivity menu
item with the following entries.

National Instruments Corporation

Menu Bar Constant Prefix

MENU

Constant Name

CASE

Item Name

Case Sensitivity

2-19

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Callback Function

SetCaseSensitivity

Modifier Key

None

Shortcut Key

No Shortcut Key

Ensure that the Edit Menu Bar dialog box is similar to the one shown
in the following figure. After you verify that your dialog box
matches the one shown, click OK. Save uiproject.uir.

3. Verify that CodeSet Target File is set to uiproject.c.


4. Use CodeBuilder to generate the callback functions for the menu.
a. Click the uiproject.uir file.
b. Select CodeGenerateMenu Callbacks.
c. In the Select Menu Bar Objects dialog box, click the Check All
button and then click OK.
d. Verify that CodeBuilder generated the following five functions in the
uiproject.c file.

LabWindows/CVI Basics II Course Manual

OpenText

SaveText

2-20

ni.com

Lesson 2

ExitProgram

FindString

SetCaseSensitivity

User Interface Programming

5. Navigate to the /*Load Menu Bar Here*/ comment in the main


function of uiproject.c.
a. Insert the LoadMenuBar function under the comment to load the
menu bar on the main panel.
b. From the Library Tree, select User Interface LibraryMenu
StructuresMenu BarsLoadMenuBar and complete the function
panel as shown in the following table. After you finish, select Code
Insert Function Call.
Destination Panel Handle

mainPanel

Filename

"uiproject.uir"

Menu Bar Resource ID

MENU

Menu Bar Handle

hMenu

c. Use the Declare Variable dialog box to declare hMenu as a global


variable at the top of uiproject.c. Press <Ctrl-D> to open the
Declare Variable dialog box and select Add declaration to top of
target file uiproject.c. Deselect the other options.
Note If prompted with a message stating that the user interface file has been modified,
then click OK.

6. Fill in the code for the menu callback functions as shown in the
following figure.

a. In the uiproject.c, navigate to the OpenText callback function


and enter ReadDataFile(); to call the function, which has

National Instruments Corporation

2-21

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

already been defined. The ReadDataFile function opens a file


dialog box, opens the selected file, reads the contents of the file, and
finally displays the contents of the file in the text box control.
b. In the SaveText callback function, enter WriteDataFile(); to
call the function, which has already been defined. The
WriteDataFile function opens a file dialog box, opens the
selected file, and writes the contents of the text box control to
the file.
c. In the ExitProgram callback function, enter
QuitUserInterface(0); to stop the application.
d. Modify the FindString callback function to load the buffer
with the text box contents, display a prompt dialog box with
PromptPopup, and call the SearchRoutine function on the
returned string. The final code for the function should be similar
to the following code.

e. The SetCaseSensitivity callback toggles case sensitivity in the


SearchRoutine. The Case Sensitive menu item is checked when
case sensitivity is active. Complete the code as shown in following
figure.

To specify ATTR_CHECKED as the attribute to set, select Menu


Item Checked for Menu Bar Attribute in Attribute Constant
dialog box. Declare the variable CaseSensitive as a global
integer variable.

LabWindows/CVI Basics II Course Manual

2-22

ni.com

Lesson 2

User Interface Programming

f. Modify the FindPattern function call to include the


CaseSensitive variable for the case sensitive argument as shown
in the following code segment:
result = FindPattern (Buffer, searchposition,
-1,FindThis,CaseSensitive, 0);

7. Save and run the project. Verify that menu functions and the command
buttons work properly.

End of Exercise 2-3

National Instruments Corporation

2-23

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Canvas Control

Arbitrary drawing port


Low-level functions
Speed and flexibility
Use for text, lines, and bitmaps

Canvas Control
The canvas control is an arbitrary drawing surface for drawing text, shapes, and bitmap images. The
major advantages of using a canvas over a graph are speed and flexibility. The canvas control
functions consist of low-level functions for bitmap manipulation and for drawing lines, text, and
points.
With graphs, you can plot static, numerical data. If you want to display items that require more
capabilities than a graph, you can take advantage of a canvas control.

LabWindows/CVI Basics II Course Manual

2-24

ni.com

Lesson 2

User Interface Programming

Graphs versus Canvases

Graphs versus Canvases


Besides their functions, graph and canvas objects differ internally. For graphs, LabWindows/CVI
keeps track of the data being plotted and handles each trace as an object. You can delete an
individual trace from a graph by passing a specific plot handle to DeleteGraphPlot. This action
is convenient but also can cause a graph to have more overhead. For a canvas, LabWindows/CVI
keeps an offscreen bitmap of the display but does not distinguish between the objects plotted. For
this reason, you cannot delete a specific trace. The only way to delete a trace is by redrawing over
the area or by clearing the entire canvas. The offscreen bitmap restores the appearance of the canvas
when the region is exposed.
You can use a graph to plot arrays of data and to display waveforms. Graphs also have built-in
features such as a built-in plot legend, anti-aliased plotting, autoscaling, graph cursors, gridlines,
axis labeling, and so on.
If you want to expand beyond waveform plotting or to implement custom displays, you can use the
canvas control.

National Instruments Corporation

2-25

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Using a Canvas
Use a canvas for the following tasks:
To draw objects using low-level primitives, such as pie charts
and Smith charts
To use and manipulate bitmaps (animation)
To avoid the overhead associated with graphs

Use a graph or strip chart for the following tasks:


To plot arrays of data
To use the scrolling capabilities of a strip chart

Using a Canvas
When deciding between the various display options available to you, choose the UI object that
provides the most built-in features for your purpose. Use graphs and strip chart controls to graph
data in standard ways and use canvas controls for specialty purposes.
One thing to remember is that graphs have a wide range of capabilities. Study the examples that
ship with LabWindows/CVI to determine the possibilities of both graphs and canvas controls.
When programming with canvas controls, remember that canvases have attributes you can change
programmatically, such as the draw policy, overlapped policy, and coordinate system. You also can
use the bitmap functions in close association with the canvas functions.

LabWindows/CVI Basics II Course Manual

2-26

ni.com

Lesson 2

User Interface Programming

Useful Type Definitions for Canvases


Many canvas functions use the Rect and Point structures to specify
locations and areas in Cartesian coordinates. These structures are
defined in userint.h as
typedef struct {
int top;
int left;
int height;
int width;
} Rect;

typedef struct {
int x;
int y;
} Point;

Useful Type Definitions for Canvases


Two structures exist for specifying locations and areas in Cartesian coordinates: Rect and Point.
These two structures are defined in userint.h as follows:
typedef struct {
int top;
int left;
int height;
int width;
} Rect;
typedef struct {
int x;
int y;
} Point;

Most canvas functions use one or more of these structures.

National Instruments Corporation

2-27

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Useful Functions for Canvases


MakeRect and MakePoint are utility functions that create
Rect and Point structures for you
Rect MakeRect (int top, int left,
int height, int width);
Point MakePoint (int x, int y);

You can embed these functions into a canvas function call to


eliminate the need to declare the structure
CanvasDrawLineTo (hPanel, PANEL_CANVAS,
MakePoint(100, 200));

Useful Functions for Canvases


When making canvas function calls, you can use one of the following functions:
Rect MakeRect (int top, int left, int height, int width);
Point MakePoint (int x, int y);

To understand these functions, consider the CanvasDrawLineTo function. This function draws a
line between the current pen position and the specified end point and sets the pen position to the
end point. The function draws the line with the current pen attributes including color, mode, width,
and style. The end point is defined by a structure of type Point, which specifies the x and y
coordinates.
CanvasDrawLineTo (hPanel, PANEL_CANVAS, MakePoint (100, 200));

This function draws a line from the current pen position to x = 100, y = 200, where the top left
corner of a canvas control is x = 0, y = 0.

LabWindows/CVI Basics II Course Manual

2-28

ni.com

Lesson 2

User Interface Programming

Canvas Functions
Located in the Library Tree under
User Interface Library
Controls/ Graphs/Strip Charts
Canvas

Canvas Functions
The canvas control functions are located in the Library Tree under User Interface Library
Controls/Graphs/Strip ChartsCanvas. You can create a wide variety of shapes with the
CanvasDraw functions. To draw a point, use CanvasDrawPoint. Other options include line,
rectangle, oval, arc, polygon, text, and bitmap.
Use CanvasSet/GetPenPosition to control an imaginary pen within the canvas control. You
can fully control the pen attributes and location. You can determine whether the pen touches the
user interface, the pen thickness and color, and so on.
Because you cannot delete individual traces on a canvas control, you must either retrace or clear
everything within a specified area. Use CanvasClear to retrace or clear the area. To update any
changes to the canvas control immediately, call CanvasUpdate.
If you make several canvas function calls in a row, nest the calls between
CanvasStartBatchDraw and CanvasEndBatchDraw because there is an associated system
overhead for each canvas function call that these functions eliminate.

National Instruments Corporation

2-29

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Exercise 2-4

OBJECTIVE

Time to complete: 30 min.

To add a canvas control to the application

LabWindows/CVI Basics II Course Manual

2-30

ni.com

Lesson 2

Exercise 2-4
Objective:

User Interface Programming

Canvas Controls

To add a canvas control that can be drawn on with the mouse.


Modify the project to allow users to draw on a canvas control. This exercise
shows how easy it is to respond to the mouse and scribble on the screen.
1. Load the uiproject.prj file located in the directory
C:\Exercises\CVI Basics II\Lesson 2\uiproject.prj.

2. Complete the following steps to add a new panel to uiproject.uir


for the drawing canvas.
a. Open uiproject.uir.
b. Add a command button to the main panel to launch the canvas panel.
Double-click the command button to open the Edit Command
Button dialog box. Complete the dialog box as shown in the
following table.
Constant Name

SHOWCANVAS

Callback Function

ShowCanvasPanel

Label

Show __Canvas

After you create the button, the main panel should be similar to the
following figure.

c. Verify that CodeSet Target File is set to <New Window>.

National Instruments Corporation

2-31

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

d. Right-click the Show Canvas button and select Generate Control


Callback, which generates the callback function for the button in
a new .c file. Leave this new .c file open.
e. Select CreatePanel to create a new panel in the uiproject.uir
file. Double-click the newly created panel and specify the following
entries.
Constant Name

CNVSPANEL

Panel Title

Canvas Drawing Panel

In the following steps, you modify the newly created panel so that it
contains a canvas control, timer control, and Close button. After you
finish the steps, your canvas should be similar to the following figure.

f. Select CreateCanvasCanvas to add a new canvas control to the


new panel. Double-click the canvas control and specify the constant
name CANVAS, the callback function DrawCanvas, and the label
Drawing Area.
g. Add a command button to the panel with the constant name CLOSE,
the callback function CloseCanvasPanel, and the label __Close.
h. Add a timer control to the panel with the constant name TIMER,
the callback function TimerTick, and the label Timer. Set the
Interval to 0.010 and disable the Enabled checkbox.
i. To generate the callback functions for the Close and Timer buttons,
right-click each control and select Generate Control Callback.
j. Before you generate the callback function for canvas drawing area,
select CodePreferencesDefault Control Events and select
EVENT_LEFT_CLICK as the only event. Click OK.

LabWindows/CVI Basics II Course Manual

2-32

ni.com

Lesson 2

User Interface Programming

k. To generate the callback functions for the canvas drawing area,


right-click the control and select Generate Control Callback.
l. Save the new .c file as canvas.c and select FileAdd canvas.c to
Project to add the file to your project.
m. Save and close the uiproject.uir file.
You now have a .c file in your project called canvas.c with four empty
callbacks. Before proceeding, set the target file to canvas.c. Complete the
following steps to write the four callback functions.
3. Place your cursor in the EVENT_COMMIT case in the
ShowCanvasPanel callback function. Write this function to display
the CNVSPANEL as a pop-up panel. You must call LoadPanel to load
the panel. From the Library Tree, select User Interface Library
PanelsLoadPanel and complete the function panel as shown in the
following table. When you finish, select CodeInsert Function Call.
Parent Panel Handle

Filename

"uiproject.uir"

Panel Resource ID

CNVSPANEL

Panel Handle

canvasPanel

Declare the variable canvasPanel at the top of canvas.c as the panel


handle.
4. From the Library Tree, select User Interface LibraryPop-up Panels
InstallPopup and enter canvasPanel as the panel handle. When you
finish, select CodeInsert Function Call.
5. At the top of the file, declare global variables that are used for drawing
in the canvas with the mouse. Add the variable declarations at the top of
the file as shown in the following figure. Include uiproject.h if it is
not included.

National Instruments Corporation

2-33

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

6. The DrawCanvas function detects when the user clicks the canvas to
start drawing. The drawing continues as long as the user continues to
hold down the left mouse button. Use the following code for this
function.

DrawCanvas starts the timer so that if the user holds down the left
mouse button, the timer callback function draws a line between the
current pen position and a specified end point. This function also obtains
the position of the mouse within the canvas and sets the canvas pen to
that position.

7. TimerTick draws a continuous line while a user holds down the left
mouse button. The code for this function is as follows.

TimerTick obtains the position of the mouse and checks the value of
the variable lButtonDown. If lButtonDown is set to true from the
DrawCanvas function, TimerTick draws a line from the previous pen
position to the current mouse position. If lButtonDown is set to false,
TimerTick turns the timer off.

LabWindows/CVI Basics II Course Manual

2-34

ni.com

Lesson 2

User Interface Programming

8. In the CloseCanvasPanel callback function, call the RemovePopup


function to close the pop up panel. To do this, select User Interface
LibraryPop-up PanelsRemovePopup from the Library Tree and
then insert the function call. To remove the panel from memory select
User Interface LibraryPanelsDiscardPanel from the Library Tree.
Enter canvasPanel as PanelHandle and then insert the function call.
9. Save the canvas.c file and run the project. Verify that the canvas panel
works properly by scribbling on it while you hold down the left mouse
button.

End of Exercise 2-4

National Instruments Corporation

2-35

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Table Control

Provides a spreadsheet-type interface


Has built-in functions to search, sort, and select data
Accepts numeric, string, or picture data types

Table Control
One of the more advanced controls in LabWindows/CVI is the table control. The table control is a
powerful and flexible tool for storing and operating on tabular data. With the table control, you can
display arrays, perform spreadsheet operations, and sort data.
The table control has built-in functionality to select and edit data, which is similar to the
functionality of a spreadsheet program. Data can be selected by row, column, or individual cell. The
table control also provides built-in searching and sorting functions and provides the ability to jump
to certain cells automatically. The table control can contain several data types including strings,
numbers, and even pictures.

LabWindows/CVI Basics II Course Manual

2-36

ni.com

Lesson 2

User Interface Programming

Table Control Components


Tables are rows and columns of cells
Columns and rows can contain labels
Customizable run-time context menu with built-in Goto,
Find, and Sort functions
Shading, gridlines, and colors are customizable
Column
Label

Context Menu

Cell
Row
Column

Table Control Components


Tables are composed of cells arranged in rows and columns. Each cell can contain a different type
of data. You can add labels to columns and rows to describe the data or show the row and column
indices. By default, the labels are set to the row or column index. Use these labels to function like
command buttons to sort data or for any other function. You can select an entire row or column by
selecting the label, which is similar to the behavior in most spreadsheet programs.
The table control also has a built-in context menu that appears when you right-click the table area.
By default, this menu lists three functions. Goto allows the user to specify a target cell to move to
by entering the target cells column and row indices. Find allows the user to enter a value to search
for in the table. Sort rearranges the selected cells of data. You can add custom functions to this
menu using NewCtrlMenuItem.
Use attributes to customize the appearance of the table control. You can change the shading, colors,
gridlines, fonts, and other visual attributes.

National Instruments Corporation

2-37

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Programming with the Table Control

You can construct tables in the User Interface Editor or programmatically:


Insert/DeleteTableColumns
Insert/DeleteTableRows

Programming with the Table Control


A table control has no cells when you first create it. To add cells, insert rows and columns into the
table in the User Interface Editor or programmatically.
In the User Interface Editor, you can add and format rows and columns and set default values for
the columns and rows or for individual cells using the Edit Table dialog box. One advantage to
setting up the table in the User Interface Editor is that you can resize the columns to fit the table
area. You also can label columns and rows in the User Interface Editor. LabWindows/CVI uses the
index values as the default labels.
To add rows and columns programmatically, use the InsertTableColumns and
InsertTableRows functions. Remove columns and rows with the DeleteTableColumns and
DeleteTableRows functions. You can get and set all of the attributes of the table and its columns,
rows, and cells programmatically with attribute functions. Use SetCtrlAttribute to set table
attributes, such as the label and scroll bar options. To set row, column, and cell attributes, use the
following custom functions:

SetTableRowAttribute

SetTableColumnAttribute

SetTableCellAttribute

LabWindows/CVI Basics II Course Manual

2-38

ni.com

Lesson 2

User Interface Programming

Programming with the Table Control (cont.)


Cells are referenced by column and row indices in a Point structure.
For example,
Point cell;
int row, column;
cell = MakePoint (column, row);

When a mouse event occurs on a table control, the cell can be found with
the following code:
Point mouse, cell;
mouse = MakePoint (eventdata2, eventdata1);
GetTableCellFromPoint (panel, TABLE,
mouse, &cell);

Programming with the Table Control (cont.)


To specify a certain cell in a table, use the row and column indices. These values are combined in
the Point structure. You can use the MakePoint function to create a cell reference from the row
and column indices.
As with other control types, all the events on the table control are processed in the table control
callback function. To find the exact cell where the event occurred, use the
GetTableCellFromPoint function with the event data. For example,
int CVICALLBACK TableCB (int panel, int control, int event, void
*callbackData, int eventData1, int eventData2)
{
Point mouse; //Mouse location
Point cell; //Cell with event
Mouse = MakePoint (eventData2, eventData1);
GetTableCellFromPoint (panel, TABLE, mouse, &cell);
...
}

National Instruments Corporation

2-39

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Exercise 2-5

OBJECTIVE

Time to complete: 30 min.

To add a table control to the application

LabWindows/CVI Basics II Course Manual

2-40

ni.com

Lesson 2

Exercise 2-5
Objective:

User Interface Programming

Table Controls

To add a table control to the application.


1. Load the uiproject.prj file located in the directory
C:\Exercises\CVI Basics II\Lesson 2\uiproject.prj.

2. Select EditAdd Files to ProjectSource (*.c) to add table.c


to the project.
3. Open table.c. This file contains a utility function called
GenerateTestData that generates the data for a row of the table.
Examine this function and how the data is generated. Leave the file
open.
4. Open uiproject.uir.
5. Add a command button to the main panel that launches the table panel.
6. Double-click the command button to open the Edit Command Button
dialog box. Complete the dialog box as shown in the following table.
Constant Name

SHOWTABLE

Callback Function

ShowTablePanel

Label

Show __Table

After you create the button, the main panel should be similar to the
following figure.

National Instruments Corporation

2-41

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

7. Make sure that CodeSet Target File is set to table.c. Before you
generate the callback function for the Show Table button, select
CodePreferencesDefault Control Events and select only
EVENT_COMMIT. Click OK. Right-click the Show Table button
and select Generate Control Callback. This command generates the
callback function for the button in the table.c file.
8. Select CreatePanel to create a new panel. Double-click the panel and
specify TABLEPANEL as the panel constant name and Table Control
Panel as the panel title.
9. Select CreateLists & TablesTable to add a table control to the new
panel. Double-click the table control to open the Edit Table dialog box.
In this dialog box, you can create rows and columns, initialize cells, and
format the table.
a. Enter Test Results as the label of the table.
b. Disable the Row Labels Visible checkbox.
c. Set the Scroll Bars option to Vertical Scroll Bar.
d. Click the Insert Column After button to add the first column to
the table.
e. Click the Edit Column button. Enable the Use Label Text
checkbox and enter Test ID in the Label textbox as shown in the
following figure.

LabWindows/CVI Basics II Course Manual

2-42

ni.com

Lesson 2

User Interface Programming

f. Click the Edit Default Cell Values button to change the Type to
Numeric and the Data Type to int.
g. Click OK to close the Edit Default Cell Values dialog box.
h. Click OK again to close the Edit Column dialog box and return to
the Edit Table dialog box.
10. Click Insert Column After button to add new column. Repeat the
process in step 9 parts d through h with the values in the following
tables.
Column 2
Width

130

Label Text

Date/Time

Cell Type

String

Numeric Data Type

int

Column 3
Width

50

Label Text

Meas. 1

Cell Type

Numeric

Numeric Data Type

double

Column 4

National Instruments Corporation

Width

50

Label Text

Meas. 2

Cell Type

Numeric

Numeric Data Type

double

2-43

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Confirm that your table has four columns and the Edit Table dialog box
is similar to the one shown in the following figure.

11. Close the Edit Table dialog box by clicking OK and size the table to
show all four columns completely.
12. Add a command button to the panel with the constant name RUNTEST,
the callback function RunTest, and the label __Run Test.
13. Add another command button to the panel with the constant name
CLOSE, the callback function CloseTablePanel, and the label
__Close.
14. For each new button, right-click the button and select Generate Control
Callback to generate the callback functions in table.c.
The completed panel should be similar to the following figure.
15. Save and close the uiproject.uir file.

LabWindows/CVI Basics II Course Manual

2-44

ni.com

Lesson 2

User Interface Programming

The table.c now contains three empty callback functions that require
modifications
16. Place your cursor in the EVENT_COMMIT case in the ShowTablePanel
callback function. You must call LoadPanel to load the panel. From the
Library Tree, select User Interface LibraryPanelsLoadPanel and
complete the function panel as shown in the following table. When you
finish, select CodeInsert Function Call.
Parent Panel Handle

Filename

"uiproject.uir"

Panel Resource ID

TABLEPANEL

Panel Handle

tablePanel

a. From the Library Tree, select User Interface LibraryPop-up


PanelsInstallPopup and enter tablePanel in the panel handle
textbox. When you finish, select CodeInsert Function Call.
b. Set the value of the global variable testID to zero in this function.
Enter testID = 0; below the InstallPopup function.
17. The RunTest callback function calls GenerateTestData to obtain
data for one row of the table. InsertTableRows inserts a row in the
table. Four function calls to SetTableCellVal place the data in the
table. The MakePoint function references a particular cell in the table
with the x-coordinate and y-coordinate position of the cell in the table.
The code for this callback is similar to the following example.

National Instruments Corporation

2-45

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

18. The CloseTablePanel callback function hides the table panel with
RemovePopup. From the Library Tree, select User Interface Library
Pop-up PanelsRemovePopup and then insert the function call.
19. To remove the panel from memory select User Interface Library
PanelsDiscardPanel from the Library Tree. Enter tablePanel as
PanelHandle and then insert the function call.
20. Save table.c and run the project. Verify that the table panel works
properly and the Run Test button adds a row of data to the table. Also,
right-click the table to try the built-in pop-up context functions.

End of Exercise 2-5

LabWindows/CVI Basics II Course Manual

2-46

ni.com

Lesson 2

User Interface Programming

Tree Control

Provides an easy way to visualize hierarchical data, such as files in a


directory structure
Has built-in functions to search, sort, and select data

Tree Control
Another advanced control in LabWindows/CVI is the tree control. The tree control is a powerful
and flexible tool for storing and operating on data that has a parent-child relationship, such as files
in a directory. With the tree control, you can easily search and sort data stored in the tree.
The tree control uses all of the same functionality as a list box control. This means that you can use
list box functions on tree controls. You also can use functions that are specific to tree controls.
These functions are located in the Library Tree under User Interface Library
Controls/Graphs/Strip ChartsList/Tree (Label/Value) ControlsTrees.
The tree control uses a row index to identify items in the tree. The first item in the tree has the row
index of zero. The second item in the tree has the row index of one, and so on. The level of the tree
item depends on whether the item is a parent, a child, or a sibling. An item that has one or more
child items associated with it is called a parent item. A child item always is indented from its parent.
Items that are at the same level are considered sibling items. An item that has no parent is a root
item and is always at the top of the hierarchy. You can expand or collapse a parent node to display
or hide its child items.
Select CreateLists & TablesTree to create a tree control in the User Interface Editor. Use the
Edit Tree dialog box to add items to the tree and to edit these items.

National Instruments Corporation

2-47

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Tree Control (cont.)

You can construct trees in the User Interface Editor or programmatically:


InsertTreeItem/DeleteListItem

Tree Control (cont.)


Use the Change Level buttons to modify an items relationship to other items in the tree. Use
controls in the Edit Tree dialog box to specify various item features including the item label, the
item mark type, whether users can interactively drag and drop the items, and the image and
collapsed image for the item. You also can create an image list and modify the control and label
appearance in the Edit Tree dialog box. Use the Advanced Tree Options dialog box, which you can
access by clicking the Advanced Tree Options button in the Edit Tree dialog box, to set other tree
options. Specify settings including whether to show images for items, whether to show the lines
connecting sibling tree items, and whether to show the plus/minus box for parent tree items.
You also can construct trees programmatically. Use the InsertTreeItem and
InsertTreeColumn functions to add items and columns to the tree. You can programmatically
get and set attributes for the tree, tree items, tree cells, and tree columns. Use the AddTreeImage
function to add images to the tree controls list of images. To associate an image from the list with
a tree item, set the image attributes of the item to the index returned by AddTreeImage. Use the
searching functions, which include GetTreeItem, GetTreeItemFromLabel, and
GetTreeItemFromTag, to search for items in a tree. Also use tree functions to find the root of a
tree item; sort, copy, and move tree items; set the active item; and get the tree index from a screen
point.
Like the table control, the tree control has a built-in context menu that appears when you right-click
the tree. The context menu has several default menu items that you can add to using the
NewCtrlMenuItem function. Remove default items from the context menu using
HideBuiltInCtrlMenuItem.

LabWindows/CVI Basics II Course Manual

2-48

ni.com

Lesson 2

User Interface Programming

Exercise 2-6

OBJECTIVE

Time to complete: 30 min.

To add a tree control to the project

National Instruments Corporation

2-49

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Exercise 2-6
Objective:

Tree Controls

To add a tree control to the project.


A tree control is a powerful way to organize complex data that is
hierarchical in nature. In this project, you will programmatically add items
to a tree. The tree in this project allows users to delete items. You can delete
only items that do not have any descendents.

Part A: User Interface


1. Load the uiproject.prj file located in the directory
C:\Exercises\CVI Basics II\Lesson 2\uiproject.prj.

2. Add a command button to the main panel that launches the tree panel.
Double-click the command button to open the Edit Command Button
dialog box. Complete the dialog box as shown in the following table.
Constant Name

SHOWTREE

Callback Function

ShowTreePanel

Label

Show __Tree

After you create the button, the main panel should be similar to the
following figure.

3. Make sure CodeSet Target File is set to <New Window>. Right-click


the Show Tree button and select Generate Control Callback.

LabWindows/CVI Basics II Course Manual

2-50

ni.com

Lesson 2

User Interface Programming

4. Create a new panel. Give the panel the constant name TREEPANEL and
the panel title Tree Control Panel.
Populate the newly created panel with a tree control and command
buttons. Create a panel similar to the following figure.

5. Add a tree control to the new panel. Right-click the panel and select
Lists & TablesTree. Double-click the tree control to open the Edit
Tree dialog box.
a. Enter Tree Test as the label of the table.
b. Assign the tree control the constant name TREE.
6. Add the Insert Child command button to the panel. Assign the button
the constant name INSERTCHILD, the callback function InsertChild,
and the label Insert __Child.
7. Add the Insert Sibling command button to the panel. Assign the button
the constant name INSERTSIBLING, the callback function
InsertSibling, and the label Insert __Sibling.
8. Add the Delete Item command button to the panel. Assign the button the
constant name DELETEITEM, the callback function DeleteItem, and
the label __Delete Item.
9. Add the Close command button to the panel. Assign the button the
constant name CLOSE, the callback function CloseTreePanel, and the
label C__lose.
10. Right-click each button and select Generate Control Callback.
11. Access the untitled .c file through the Window menu. Save the new
.c file as tree.c. Add the file to the project by selecting FileAdd
tree.c to Project.
12. Save the uiproject.uir file.

National Instruments Corporation

2-51

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Part B: Code
The tree.c now contains five empty callback functions that require the
following modifications.
1. Use LoadPanel to modify the ShowTreePanel function to launch the
TREEPANEL.
a. Complete the function panel as shown in the following table.
Parent Panel Handle

Filename

"uiproject.uir"

Panel Resource ID

TREEPANEL

PanelHandle

treePanel

b. Insert the function call.


c. Enter static int treePanel; at the top of the tree.c to store
the panel handle for the tree panel.
2. Use InstallPopup to modify the ShowTreePanel function to launch
the TREEPANEL. Enter panel handle as treePanel and insert the
function call.
3. Enter static int index; at the top of tree.c. Set the value of
index equal to 1 in the ShowTreePanel function. The variable
index keeps track of the location of the item that is inserted.
4. In the InsertChild callback function, call the InsertTreeItem
function. Select User Interface LibraryControls/Graphs/Strip
ChartsLists/Tree (Label/Value) ControlsTreesInsertTreeItem
and complete the function panel as shown in the following table. When
you finish, select CodeInsert Function Call.
Panel Handle

treePanel

Control ID

TREEPANEL_TREE

Relation

Child

Relative Index

index

Position

Last

Item Label

"Child"

Tag Base

LabWindows/CVI Basics II Course Manual

2-52

ni.com

Lesson 2

Tag

Item Value

index

User Interface Programming

This function inserts an item as a descendent of the item before it. If the
item is the first item to be inserted into the tree, the function ignores the
Relation parameter and always inserts the item as a parent item.
5. Enter index = index + 1; to increment the value of index by one
after the child item is inserted into the tree.
6. In the InsertSibling callback function, call the InsertTreeItem
function as you did in step 4. Complete the function panel as shown in
the following table and insert the function call.
Panel Handle

treePanel

Control ID

TREEPANEL_TREE

Relation

Sibling

Relative Index

index

Position

Last

Item Label

"Sibling"

Tag Base

Tag

Item Value

index

This function inserts an item at the same level as the last item placed into
the tree. If the inserted item is the first to be inserted into the tree, the
function ignores the Relation parameter and inserts the item as a parent
item.
7. Enter index = index + 1; to increment the value of index by one
after the sibling item is inserted into the tree.
8. In the DeleteItem callback function, you want to implement code that
deletes only an item that has been selected by the user. Only items that
do not have any descendents can be deleted. This step shows how you
also can use the list functions to control the tree control.

National Instruments Corporation

2-53

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Add the following code to the DeleteItem callback function.

Complete the DeleteItem function using the following steps


a. Call GetActiveTreeItem to determine which item the user has
selected. Select User Interface LibraryControls/Graphs/Strip
ChartsList/Tree (Label/Value) ControlsTrees
GetActiveTreeItem and complete the function panel as shown in
the following table. When you finish, select CodeInsert Function
Call.
Panel Handle

treePanel

Control ID

TREEPANEL_TREE

Active Index

&active

Enter int active; inside the DeleteItem function to declare


active as variable. GetActiveTreeItem returns the location of
the item in the tree that the user selects. If the user does not select an
item or there are no items in the tree, the function returns 1.
b. Test the value of active to make sure that an item exists and that
the user has selected an item. To test the value of active, select
EditInsert ConstructIf and enter active > 1 for the
Condition. Click OK when done.
c. In the if statement, call GetTreeItemNumDescendents to
determine if the item selected has any descendents. Select User
Interface LibraryControls/Graphs/Strip ChartsList/Tree
(Label/Value) ControlsTreesGetTreeItemNumDescendents

LabWindows/CVI Basics II Course Manual

2-54

ni.com

Lesson 2

User Interface Programming

and complete the function panel as shown in the following table.


When you finish, select CodeInsert Function Call.
Panel Handle

treePanel

Control ID

TREEPANEL_TREE

Item Index

active

Number of Descendents

&descendents

Enter int descendents; inside the DeleteItem function. If an


item has any descendents, GetTreeItemNumDescendents
returns a positive non-zero number.
d. To check if the number of descendents is equal to zero, select Edit
Insert ConstructIf and enter descendents == 0 for the
Condition. Click OK when done. Inside the if statement, call
DeleteListItem. This function illustrates how you can use list
functions on trees. Select User Interface Library
Controls/Graphs/Strip ChartsList/Tree (Label/Value)
ControlsDeleteListItem and complete the function panel as
shown in the following table. When you finish, select CodeInsert
Function Call.
Panel Handle

treePanel

Control ID

TREEPANEL_TREE

Item Index

active

Number of Items

e. When the item has been deleted, subtract one from the variable
index, since an item has been removed from the tree. To do this,
enter index = index - 1; in the if statement. Remember that
the variable index indicates where the item needs to be placed into
the tree when a child or sibling is inserted into the tree.
9. The CloseTreePanel callback function hides and removes the panel
from memory with RemovePopup and DiscardPanel as in the
previous exercise.
10. Save tree.c and run the project. Verify that the tree functions correctly.
Later in the course you will create a tree control that displays a directory
listing of the files on your computer.

End of Exercise 2-6

National Instruments Corporation

2-55

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Intensity Graphs

Useful in displaying terrain and temperature patterns,


spectrum analysis, and image processing
Use a standard graph control to display the intensity graph
Use the PlotIntensity function
Intensity Graphs
You can use intensity graphs to display patterned data such as temperature patterns and terrain.
Use the PlotIntensity function with a standard graph control to create an intensity graph.
PlotIntensity draws a solid rectangular plot in a graph control. The plot consists of pixels
whose colors correspond to the magnitude of data values in a two-dimensional array and whose
coordinates correspond to the locations of the same data values in the array. For instance, the pixel
associated with zArray[2][3] is located at {x = 3, y = 2}. Use PlotScaledIntensity to apply
scaling factors and offsets to the data values.

LabWindows/CVI Basics II Course Manual

2-56

ni.com

Lesson 2

User Interface Programming

Intensity GraphsPlotIntensity Function


int PlotIntensity (int hPanel, int controlID,
void *Z_Array, int X_Points, int Y_Points,
int dataType, ColorMapEntry colorMapArray[],
int hiColor, int NumColors, int interpColors,
int interpPixels);
Z_Array is

a two-dimensional array containing the


values to be plotted. Each element in the array is
mapped to a specific x-y coordinate in the format:
z[y][x]
z[1][2] = 10.0;

At x = 2, y = 1, the color assigned to the value 10


is plotted. Colors are defined in the colorMapArray
parameter

Intensity GraphsPlotIntensity Function


Z_Array is a two-dimensional array that contains the data values to be plotted. Each element in
the array is mapped to a specific x-y coordinate in the format: z[y][x].
X_Points is an integer that contains the number of elements to be plotted along the x-axis.
Y_Points is an integer that contains the number of elements to be plotted along the y-axis.
Note

Remember that the z-array uses [y][x] values rather than [x][y].

For example, if an array value is given by z[1][2] = 10.0, at x = 2, y = 1, PlotIntensity


plots whatever color is assigned to a data value of 10.
colorMapArray defines how to translate these data values into color values. It is an array of 255.
ColorMapEntry structures that are defined are as follows:
typedef struct
{
union
{
char valChar;
int valInt;
short valShort;
float valFloat;
double valDouble;
unsigned char valUChar;

National Instruments Corporation

2-57

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

unsigned long valULong;


unsigned short valUShort;
} dataValue;
int color;
} ColorMapEntry;

LabWindows/CVI Basics II Course Manual

2-58

ni.com

Lesson 2

User Interface Programming

Intensity GraphsColor Map Array


colorMapArray is an array of 255 ColorMapEntry structures
containing values and the colors representing each value. For example,
use the following code to assign the color black to the value 0.0 and the
color white to the value 10.0:
static ColorMapEntry colors[2];
colors[0].dataValue.valDouble = (0.0);
colors[0].color = MakeColor (0, 0, 0);
colors[1].dataValue.valDouble = (10.0);
colors[1].color = MakeColor (255, 255, 255);
MakeColor returns a color based on the R (red), G (green),

and B (blue) values passed to it

Intensity GraphsColor Map Array


colorMapArray is an array of 255 ColorMapEntry structures. It defines how to translate data
values in zArray into color values. With the colorMapArray parameter for PlotIntensity, you
can specify up to 256 color entries. Depending on the operating system video mode,
LabWindows/CVI might be limited to colors in the current color palette. For systems with only
256 colors, LabWindows/CVI is forced to use most of the system color palette, which might not
contain all the colors the color map requests. For example, to plot a grayscale spectrum from black
to white using a system with 256 colors, LabWindows/CVI displays 11 gray bands to transition
from black to white. This is because the LabWindows/CVI color palette has 11 shades of gray,
including black and white. If you run the same program on a computer with 16-bit color
capabilities, you see a smooth transition from black to white. This is because the computer has
many more colors available, providing finer granularity.

National Instruments Corporation

2-59

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Exercise 2-7

OBJECTIVE

Time to complete: 30 min.

To add an intensity graph control to the project

LabWindows/CVI Basics II Course Manual

2-60

ni.com

Lesson 2

Exercise 2-7
Objective:

User Interface Programming

Intensity Graph Controls

To add an intensity graph control to the project.


1. Load the uiproject.prj file located in the directory
C:\Exercises\CVI Basics II\Lesson 2\uiproject.prj.

2. Open the intgraph.c file and add it to the project. This file contains a
utility function called GenerateData, which generates the data for the
intensity graph. Examine this function and how the data is generated.
Leave the file open in the Source window.
3. Open the uiproject.uir file.
a. Add a command button to the main panel that launches the tree
panel. Double-click the command button to open the Edit Command
Button dialog box. Complete the dialog box as shown in the
following table.
Constant Name

SHOWGRAPH

Callback Function

ShowGraphPanel

Label

Show __Graph

After you create the button, the main panel should be similar to the
following figure.

b. Make sure that CodeSet Target File is set to intgraph.c.

National Instruments Corporation

2-61

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

c. Right-click the button and select Generate Control Callback to


generate the callback function for the button in the intgraph.c
file.
4. Create a new panel that contains the intensity graph. Assign the panel
the constant name GRAPHPANEL and the panel title Intensity Graph
Panel. Complete the intensity graph as shown in the following figure.

a. Add a graph control to the panel with the constant name INTGRAPH
and a label of Intensity Graph.
b. Add a command button to the panel with the constant name PLOT,
the callback function PlotData, and the label __Plot.
c. Add a command button to the panel with the constant name CLOSE,
the callback function CloseGraphPanel, and the label __Close.
d. Right-click each button and select Generate Control Callback to
generate the callback functions in intgraph.c.
e. Save and close the uiproject.uir file.
5. Write the three new callback functions.
a. Write the ShowGraphPanel callback function to display the
GRAPHPANEL panel. Use LoadPanel to load the panel and use
InstallPopup to display the panel. Use the variable graphPanel
as the Panel Handle for the Intensity Graph Panel. Finally, insert the
function call.
b. Write the PlotData callback function to call GenerateData and
then plot the data with the PlotIntensity function.
c. Enter GenerateData(); in the PlotData callback function.
d. Select User Interface LibraryControls/Graphs/Strip Charts
Graphs and Strip ChartsGraph Plotting and Deleting
PlotIntensity and complete the function panel as shown in the

LabWindows/CVI Basics II Course Manual

2-62

ni.com

Lesson 2

User Interface Programming

following table. When you finish, select CodeInsert Function


Call.
Panel Handle

graphPanel

Control ID

GRAPHPANEL_INTGRAPH

Z Array

dataPoints

Number of X Points

XPOINTS

Number of Y Points

YPOINTS

Z Data Type

double precision

Color Map Array

colors

HiColor

HICOLOR

Number of Colors

COLORS

Interp Colors?

Interp Pixels

e. Write the CloseGraphPanel callback function to hide and remove


the panel from memory using RemovePopup and DiscardPanel
function.
f. Run the program and test the intensity graph panel. The graph
should be similar to the following figure when you click Plot.

6. (Challenge) Write your own data generation function that creates the data
and the Color Map Array for the PlotIntensity function.

End of Exercise 2-7


National Instruments Corporation

2-63

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

User-Defined Custom Controls


Create custom controls
Save these controls for use in later sessions
Rename, delete, and update previously created custom
controls for session-specific applications

User-Defined Custom Controls


You can create custom controls to save control configurations. To create a custom control, create a
control as you normally would. Then select CreateCustom ControlsEdit to open the Edit
Custom Controls dialog box.
In the Edit Custom Controls dialog box, click Add to open a dialog box that contains a list of all
the controls on the user interface panel. Select the control you want to add as a custom control and
click the OK button. The control you add appears in the CreateCustom Controls submenu.
LabWindows/CVI saves your list of custom controls between sessions. You can rename, delete,
edit, and move your custom controls in the Edit Custom Controls dialog box.

LabWindows/CVI Basics II Course Manual

2-64

ni.com

Lesson 2

User Interface Programming

Predefined Custom Controls


LabWindows/CVI allows the extension of the user interface
through instrument drivers
These extensions, referred to as predefined custom
controls, can provide unique features to enhance
your GUI
Examples include path controls, password controls, combo
boxes, file browsers, toolbars, and so on

Predefined Custom Controls


Instrument drivers are normally thought of as a collection of functions that hides the low-level
complexity of a stand-alone instrument command set. NI provides hundreds of drivers for quickly
communicating with instruments. However, you can generalize the instrument driver concept as a
collection of functions that hides the low-level complexity of functions in general.
LabWindows/CVI ships with several instrument drivers, such as a password control, which allows
you to mask characters that users enter. These special instrument drivers are known as predefined
custom controls and are located in the C:\Program Files\National Instruments\CVI\
toolslib\custctrl directory.
Examples of predefined custom controls include path controls, password controls, combo boxes,
and file browsers. You can access these controls by selecting CreateCustom ControlsToolslib
Controls in the User Interface Editor. When you generate code for your application using
CodeBuilder, LabWindows/CVI loads the appropriate instrument driver into your project. The
custom controls are ready to use. The rest of this lesson discusses predefined custom controls that
ship with LabWindows/CVI.
You cannot view instrument driver function panels until you or CodeBuilder loads
the drivers into the project.
Note

National Instruments Corporation

2-65

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Predefined Custom ControlsPath Control


Matching files and directory
paths appear
Keeps file history
You can specify file types

Predefined Custom ControlsPath Control


Select CreateCustom ControlsToolslib ControlsPath Control to add a path control to your
GUI. Use the path control to enter file and directory paths. As you type in the path control,
matching files and directories appear in the drop-down list.
The path control keeps a history of the paths entered in the control. The history stores paths that
you have selected, which you can access using the arrow keys.
You can specify the file specification and the type of files that appear in the path control using the
SetPathCtrlAttribute function.

LabWindows/CVI Basics II Course Manual

2-66

ni.com

Lesson 2

User Interface Programming

Predefined Custom ControlsPassword Control


Password controls are special controls that mask the characters that
users type
Create password controls by selecting CreateCustom
ControlsToolslib ControlsPassword Control in the User
Interface Editor
Create password controls programmatically using the
PasswordCtrl_Create and
PasswordCtrl_ConvertFromString functions in C:\Program
Files\NationalInstruments\CVI\toolslib\custctrl\pw
ctrl.fp

Predefined Custom ControlsPassword Control


There are occasions when you must add security features to your application. Also, depending on
the login level, you can expose different features of your application based upon a password
entered.
LabWindows/CVI provides this security in the form of a password control. Users can enter
characters, but the characters they enter are masked with a special character, usually an asterisk.
With LabWindows/CVI, you can change the mask character used.
Create a password control by selecting CreateCustom ControlsToolslib ControlsPassword
Control in the User Interface Editor. You also can create password controls programmatically
using the PasswordCtrl_Create and PasswordCtrl_ConvertFromString functions in
pwctrl.fp. Call PasswordCtrl_Set/GetAttribute to set and retrieve password control
attributes.
Note Instrument drivers use their own Set/GetAttributes or Values functions. You
encounter problems if you start mixing and matching functions from the User
Interface Library and instrument drivers. For example, if you use
PasswordCtrl_GetAttribute to obtain the password value entered, do not reset
the password control to an empty string using SetCtrlVal. Instead use
PasswordCtrl_SetAttribute.

National Instruments Corporation

2-67

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Predefined Custom ControlsCombo Box


Combines functionality of string and ring controls
Adds values entered into string to ring values
Any string control can be converted to a
combo box

Predefined Custom ControlsCombo Box


A combo box control combines the functionality of a string control and a ring control. Combo
boxes allow the user to enter values while maintaining a list of values that can be used to
automatically fill the string. The address bar of an internet browser is an example of a combo box.
Create a combo box in the User Interface Editor by selecting CreateCustom ControlsToolslib
ControlsCombo Box. You also can create a combo box using the functions in CVI\toolslib\
custctrl\combobox.fp. You can convert any string control into a combo box
programmatically with the Combo_NewComboBox function. To add an item to the ring list of a
combo box, use the Combo_InsertComboItem function. When the user enters new strings into
the combo box, these strings also are added to the ring list. Attributes of the combo box, such as
text color, can be set or retrieved programmatically with the Combo_SetComboAttribute and
Combo_GetComboAttribute functions.

LabWindows/CVI Basics II Course Manual

2-68

ni.com

Lesson 2

User Interface Programming

Predefined Custom ControlsFile Browser


Place a tree-based file
browser into your
application

Predefined Custom ControlsFile Browser


LabWindows/CVI implements the file browser control as a custom control instrument driver. You
can create a file browser in the User Interface Editor by selecting CreateCustom Controls
Toolslib ControlsFile Browser. You can convert any tree control into a file browser
programmatically with the FileBrowser_Create function. To set or retrieve file browser
attributes programmatically, use the FileBrowser_SetAttribute and
FileBrowser_GetAttribute functions. Use C:\Program Files\National
Instruments\CVI\toolslib\custctrl\FileBrowser.fp to access the file browser
functions.

National Instruments Corporation

2-69

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Exercise 2-8

OBJECTIVE

Time to complete: 25 min.

To use the file browser custom control in an


application

LabWindows/CVI Basics II Course Manual

2-70

ni.com

Lesson 2

Exercise 2-8
Objective:

User Interface Programming

Predefined Custom Controls

To use a predefined custom control to quickly add powerful user interface features
to an application.
This project shows how you can use a LabWindows/CVI custom control in
an application. In the project, you will use the File Browser custom control
to add a File Manager to an application.
1. Create a new project in LabWindows/CVI and save the project as
C:\Exercises\CVI Basics II\Lesson 2\
CustomControl.prj.

2. Create a new user interface file by selecting FileNewUser Interface


(*.uir).
3. Change the panel title to File Manager.
4. Build the following user interface, which contains a command button
and a File Browser custom control.

a. Place a QUIT button on the panel by selecting CreateCustom


ControlsQuit Button.
b. Place a File Browser on the panel by selecting CreateCustom
ControlsToolslib ControlsFile Browser. Double-click the File
Browser control to open the Edit Tree dialog box. Change the Label
to File Manager.
5. Save the user interface as CustomControl.uir.
6. Generate the code for the user interface by selecting CodeGenerate
All Code. In the Target Files section of the Generate All Code dialog
box, select Add to Current Project. Verify that the source filename is
CustomControl.c. Confirm that PANEL is checked in the Select
panels to load and display at startup section of the dialog box.

National Instruments Corporation

2-71

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Confirm that QuitCallback is selected in the Select QuitUserInterface


Callbacks box. Click OK.
7. LabWindows/CVI generates code for the user interface. Look at the
main function in CustomControl.c. Notice that CodeBuilder
inserted a call to FileBrowser_Create below the LoadPanel
function. The FileBrowser_Create function converts the tree
control into a File Browser.
You can add a custom control to a pre-built user interface. In order to generate code
for the custom control, right-click the custom control and select Generate Custom
Control Code from the context menu.
Note

8. Run the project.


9. When you finish the project, save and close all files.

End of Exercise 2-8

LabWindows/CVI Basics II Course Manual

2-72

ni.com

Lesson 2

User Interface Programming

Predefined Custom ControlsToolbar


Add toolbars to your application
Each picture button is an 18 18 pixel image
Supported image types include
.wmf, .bmp, .pcx, .ico, .jpg, and .png
You must load toolbars onto a panel
Toolbar buttons have callbacks like menus and controls

Predefined Custom ControlsToolbar


Using the toolbar instrument driver, C:\Program Files\National Instruments\CVI\
toolslib\custctrl\toolbar.fp, you can create and use toolbars in your programs. Toolbars
are not accessible through the User Interface Editor. You must manually load the toolbar instrument
driver into your project.
A toolbar consists of a series of picture buttons aligned across the top of the panel, below the menu
bar. Each picture button is an 18 18 pixel image. Supported image types include .wmf, .bmp,
.pcx, .ico, .jpg, and .png. Toolbar buttons work like command buttons or menu items. When
the user causes an event, a callback function is executed..
You can create .ico images with the LabWindows/CVI Icon Editor, accessible
through the User Interface Editor Tools menu.
Note

National Instruments Corporation

2-73

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Predefined Custom ControlsToolbar


Functions
To access toolbar functions, load
C:\Program Files\National Instruments\CVI\
toolslib\custctrl\toolbar.fp

Use the following functions:


Toolbar_InsertItemAdds an item to the toolbar
Toolbar_DisplayDisplays the toolbar on a panel
Toolbar_NewAllocates resources for a new toolbar
Toolbar_SetItemValSets the value for a toolbar button

Predefined Custom ControlsToolbar Functions


The functions in the toolbar instrument driver are divided into two classes: Toolbar functions and
Toolbar Item functions. You create and use a toolbar with the following function:
int Toolbar_New (int parentPanel, int menuBar, const char *title, int
top, int left, int conformBitmapColors, int conformToSystem,
ToolbarType *newToolbar);

This function creates a new toolbar on the specified panel at the position specified by top and left.
menuBar is the menu handle associated with the toolbar, if any. newToolbar is the toolbar handle
for the new toolbar (passed by reference).
The Toolbar_Display function displays the toolbar. If the toolbars parent panel is not visible,
the toolbar does not appear until the parent is displayed.
To set a particular toolbar item value, use Toolbar_SetItemVal.
The following function adds items to the toolbar:
int Toolbar_InsertItem (ToolbarType toolbar, int position, int itemType,
int active, const char *description, int callbackType, int
menuItem, CtrlCallbackPtr controlCallbackFunction, void
*callbackData, const char *imageFile);

toolbarThe handle returned from Toolbar_New.

positionSpecifies where in the toolbar the button is placed, relative to other buttons.

LabWindows/CVI Basics II Course Manual

2-74

ni.com

Lesson 2

User Interface Programming

itemTypeThe control type of the item, which can be a command button, toggle button,
separator, or ring.

activeSpecifies whether the item is visible.

descriptionA string describing the button. This string appears when the user holds the
mouse cursor over the given button.

callbackTypeSpecifies the type of callback function associated with the toolbar item like
control callback, menu callback, or no callback.

menuItemThe Control ID for the menu item that the button is associated with if
callbackType is set to menu callback. Otherwise, this parameter is ignored.

controlCallbackFunctionThe name of the control callback executed when an event occurs


on the button if callbackType is set to control callback.

callbackDataA pointer to user-defined data.

imageFileThe filename, including any path, of the image for the button.

National Instruments Corporation

2-75

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Exercise 2-9

OBJECTIVE

Time to complete: 25 min.

To add toolbar functionality to the project

LabWindows/CVI Basics II Course Manual

2-76

ni.com

Lesson 2

Exercise 2-9
Objective:

User Interface Programming

Toolbars

To add toolbar functionality to the project.


In this exercise, you will use a LabWindows/CVI built-in instrument driver
to add toolbar functionality to the user interface of your application. Adding
toolbar icons provides flexibility and ease-of-use to the end user.
1. Load the uiproject.prj file located in the directory
C:\Exercises\CVI Basics II\Lesson 2\uiproject.prj.

2. To load the toolbar instrument driver, right-click the Instruments tree


and select Load Instrument. In the Load Instrument dialog box,
navigate to C:\Program Files\National Instruments\
CVI\toolslib\custctrl and double-click toolbar.fp.
3. Declare a handle for the toolbar as a global variable at the top of
uiproject.c with static ToolbarType hToolbar;
4. In the main function, use Toolbar_New to create the toolbar. Add
Toolbar_New after your call to LoadMenuBar. From the Library Tree,
select InstrumentsToolbarToolbar functionsNew and complete
the function panel as shown in the following table. When you finish,
select CodeInsert Function Call.
Parent Panel

mainPanel

Menu Bar

hMenu

Title

"Search Toolbar"

Top

Left

Conform Bitmap Colors

Yes

Conform to System

Yes

New Toolbar

&hToolbar

Note Remember that hMenu was declared in Exercise 2-3. The toolbar functions can
use the existing callback functions that are defined with the menu for toolbar callbacks.
This is the reason for specifying the Menu Bar parameter when you create a new toolbar.

5. Add the toolbar items. The toolbar shows five buttons and
two separators as shown in the following figure.

National Instruments Corporation

2-77

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

a. Make sure that CodeSet Target File is set to uiproject.c. To


create the Open File button, select InstrumentsToolbarToolbar
Item FunctionsInsertItem and complete the function panel as
shown in the following table.
Toolbar

hToolbar

Position

Description

"Open Text File"

Active

Yes

Item Type

Command Button

Callback Type

Menu Callback

Menu Item

MENU_FILE_OPEN

Control Callback Function

Callback Data

Image File

"buttons\\open.pcx"

b. Select CodeInsert Function Call to add the function into the


source code. Using the preceding information as a template, add the
rest of the items to the toolbar with the same function. The necessary
changes to the arguments are listed in the following tables.
Save File button
Position

Description

"Save Text File"

Menu Item

MENU_FILE_SAVE

Image File

"buttons\\save.pcx"

First Separator
Position

Description

""

LabWindows/CVI Basics II Course Manual

2-78

ni.com

Lesson 2

Item Type

Separator

Callback Type

No Callback

Menu Item

Image File

""

User Interface Programming

Find button
Position

Description

"Find"

Item Type

Command Button

Callback Type

Menu Callback

Menu Item

MENU_SEARCH_FIND

Image File

"buttons\\find.pcx"

Case Sensitivity button


Position

Description

"Case Sensitivity"

Item Type

Toggle Button

Menu Item

MENU_SEARCH_CASE

Image File

"buttons\\case.bmp"

Second Separator

National Instruments Corporation

Position

Description

""

Item Type

Separator

Callback Type

No Callback

Menu Item

Image File

""

2-79

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Terminate Program button


Position

Description

"Terminate Program"

Item Type

Command Button

Callback Type

Menu Callback

Menu Item

MENU_FILE_EXIT

Image File

"buttons\\stop.pcx"

6. To display the toolbar, from the Library Tree, select Instruments


ToolbarToolbar functionsDisplay. Pass hToolbar to the function.
7. To toggle the case sensitivity button, insert the following function in
the SetCaseSensitivity function:
Toolbar_SetItemVal (hToolbar, 5, CaseSensitive);

8. Save and run the program. When LabWindows/CVI prompts you to add
the necessary include file at the top of the file, select Yes. Verify that the
toolbar is present and functions properly.

End of Exercise 2-9

LabWindows/CVI Basics II Course Manual

2-80

ni.com

Lesson 2

User Interface Programming

Predefined Custom ControlsOther Controls


Graph cursorsAllow users to select points, obtain
coordinate information, and zoom in and out of a graph
Animation controlModified canvas for playback of
animation with multiple images
NI-DAQmx I/O controlsAllow users to browse tasks,
channels, scales and so on

Predefined Custom ControlsOther Controls


Other custom control instrument drivers are available in the C:\Program Files\National
Instruments\CVI\toolslib\custctrl directory. You can access these custom controls by
selecting CreateCustom ControlsToolslib Controls.
Graph cursors allow users to select points on a plot, obtain coordinate information, and zoom in
and out of the graph at a specific point. Select CreateCustom ControlsToolslib Controls
Graph Cursors to add graph cursors to your GUI.
Another custom control is the animation control. This control is a picture ring that automatically
advances through the images. The rate of playback, stop conditions, and other attributes can be set
and retrieved programmatically. Create an animation control by selecting CreateCustom
ControlsToolslib ControlsAnimation Control.
If you installed support for NI-DAQmx in LabWindows/CVI, you also can use various NI-DAQmx
I/O controls. Use these controls to browse tasks, channels, scales, and so on. To access NI-DAQmx
I/O controls, select CreateCustom ControlsNI-DAQmx IO Controls.

National Instruments Corporation

2-81

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Summary Lesson 2
Lesson 2 describes several user interface features that enhance standard
LabWindows/CVI GUI application development.
User interface features
Attributes
Menus
Canvas controls
Table controls
Tree controls
Intensity graphs
User-defined custom controls
Predefined custom controls
Remember that you can create your own custom controls.

Summary Lesson 2
After completing the exercises in this lesson, you are now familiar with a wide assortment of user
interface featuresattribute programming, menus, custom controls, and other user interface
objects. The purpose of the lesson is not only to help you learn about these user interface features
but also to help you become more familiar with LabWindows/CVI user interface programming
style. The LabWindows/CVI programming methodology is consistent, which helps you move from
user interface programming to instrumentation-based programming quickly.

LabWindows/CVI Basics II Course Manual

2-82

ni.com

Lesson 2

User Interface Programming

Notes

National Instruments Corporation

2-83

LabWindows/CVI Basics II Course Manual

Lesson 2

User Interface Programming

Notes

LabWindows/CVI Basics II Course Manual

2-84

ni.com

Interapplication Communication and


ActiveX Automation

Lesson 3: Interapplication Communication and


ActiveX Automation

A.
B.
C.
D.

Controlling software servers through ActiveX Automation


Transferring live data through DataSocket
Interfacing with LabVIEW
Communicating over a network through TCP

Introduction
In interapplication communication, concurrently running applications communicate with each
other. Communication involves sharing data or higher-level tasks such as initiating actions in other
applications, sending events, and so on. In this lesson, you will learn about popular technologies
used to implement interapplication communication, including ActiveX Automation, TCP, and
DataSocket.
You also will learn how to use ActiveX Automation to extend the functionality of an application
by reusing code from a separate application that implements the desired functionality. This chapter
describes in brief Microsofts ActiveX technology.
Complete description of the ActiveX technology is beyond the scope of this course.

National Instruments Corporation

3-1

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

ActiveX Technologies
ActiveX is a set of technologies that uses the
Microsoft Component Object Model (COM)
ActiveX technologies include
ActiveX controls in containers
ActiveX documents
ActiveX Automation
ActiveX Technologies
ActiveX technologies are a diverse set of technologies based on the Microsoft Component Object
Model (COM). The COM standard allows developers to create code and applications from many
different languages and build a defined interface to that code, making the code easily accessible to
other applications. An application can access another applications functionality through standard
interfaces.
The following list presents common ActiveX technologies:

ActiveX ControlsA control is an object that resides on a panel to accept input from the user
and to display information. ActiveX controls are components external to LabWindows/CVI,
which can be used in the same way as built-in LabWindows/CVI controls. ActiveX controls
vary in the functionality they provide. For example, an ActiveX control might store and
manipulate different types of data for word processing and report generation, for mathematical
calculations, or to access the internet. An application that houses an ActiveX control is called
the control container. The control container communicates with the control through methods
and properties. Thus, you can use Interactive objects, such as the calendar control, in
containers, such as Web browser.

ActiveX DocumentsEnable users to view documents, such as Microsoft Word documents or


Excel spreadsheets, in an ActiveX container, such as a LabWindows/CVI panel.

ActiveX AutomationUse of one applications code/functionality, in the form of methods


and properties inside an exported object, from inside another application.

LabWindows/CVI Basics II Course Manual

3-2

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Client - Server Relationship

Application
ActiveX Client

Component
uses

Methods & Properties


ActiveX Server

Client-Server Relationship
The application and the component have a client-server relationship. The application acts as a
client that uses the component services.

National Instruments Corporation

3-3

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Type Library and Interfaces


To create and access objects, clients need
information about the server objects, properties,
and methods
This information is available from the type library of
that application. Usually has .tlb extension
A client connects to a component through a COM
interface

Type Library
To create and access objects, automation clients need information about a server objects,
properties, and methods. Often, properties have data types, and methods return values and accept
parameters. The documentation of the server application contains extensive information about the
exposed objects, methods, and properties.
A list of exposed objects is provided in the application type library. A type library contains
specifications for all objects, methods, or properties exposed by an automation server. The type
library file usually has a .tlb filename extension.
When LabWindows/CVI acts as an ActiveX client, it uses information in the servers type library
to generate wrapper code that can be used to control the server. This wrapper code is organized as
a LabWindows/CVI instrument driver.
Interfaces
A COM interface is a group of related functions that forms the means of communication between
a client and a server.

LabWindows/CVI Basics II Course Manual

3-4

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

ActiveX Automation Client-Server


Architecture
Automation Client

Step 1. reads from

Registry
Server A
Object 1

Step 2. interfaces with


Type Lib 1

Server A
Step 3. instantiates Object 2
Step 2. interfaces with
Type Lib 2

Server B
Object
Step 3. instantiates

ActiveX Automation Client-Server Architecture


Microsofts ActiveX technology provides a standard model for sharing and reusing code between
different applications written in different languages. LabWindows/CVI supports ActiveX
Automation technology. This chapter briefly describes Microsofts ActiveX technology. A
complete description of this technology is beyond the scope of this course.

National Instruments Corporation

3-5

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

ActiveX Features in LabWindows/CVI


ActiveX
Client
(Visual Basic,
Visual C++,
LabVIEW,
LabWindows/CVI)

ActiveX
Control

Automation

ActiveX
Server
(LabWindows/CVI)

Containment

(component controls)

ActiveX
Container
(Visual C++,
LabVIEW,
LabWindows/CVI)

ActiveX Features in LabWindows/CVI


LabWindows/CVI supports ActiveX Automation technology. For example, you can create ActiveX
Automation clients using LabWindows/CVI to access other ActiveX Automation servers, such as
Microsoft Word and Excel, LabVIEW, and so on.
ActiveX Automation servers also can publish events to clients. In LabWindows/CVI, events from
the automation server can be set with callback functions and handled like any other event in the
application. For example, the ActiveX automation server for Microsoft Excel sends an event back
to the client if the user closes a worksheet. The client program in LabWindows/CVI can capture
the close worksheet event from the Excel automation server and not allow the worksheet to close
or respond in any other way.
You also can access LabWindows/CVI as an automation server from other automation clients. You
can use the LabWindows/CVI automation server to load and build LabWindows/CVI projects from
another program.
Containment occurs when an application acts as an ActiveX container, meaning that the application
contains objects from other software packages. ActiveX containers can contain both controls and
documents. Controls are ActiveX objects that you can act on directly. Documents are objects that
you can either link to or embed in a container.

LabWindows/CVI Basics II Course Manual

3-6

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

LabWindows/CVI as ActiveX Container

Windows media player as


ActiveX Object (control)

LabWindows/CVI as
ActiveX Container

LabWindows/CVI as ActiveX Container


LabWindows/CVI can create an application that acts as an ActiveX container and houses an
ActiveX control. For example, in the above example, Windows Media Player is an ActiveX control.
In Exercise 3-2, you will see how to create this type of application in LabWindows/CVI.

National Instruments Corporation

3-7

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

LabWindows/CVI as Automation Client


LabWindows/CVI creates
ActiveX client.
Microsoft Internet Explorer
acts as ActiveX
automation server.

LabWindows/CVI as Automation Client


You can use LabWindows/CVI to create an ActiveX client that accesses other ActiveX automation
servers. The LabWidnows/CVI ActiveX client application launches Microsoft Internet Explorer,
loads a Web page in the browser, and closes the browser. You will create an ActiveX automation
client in Exercise 3-3.

LabWindows/CVI Basics II Course Manual

3-8

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

LabWindows/CVI as Automation Server


LabWindows/CVI acts as
ActiveX server

LabWindows/CVI as Automation Server


You can use LabWindows/CVI as an ActiveX automation server that other ActiveX automation
clients can control. Exercise 3-4 demonstrates how to use an ActiveX server and an ActiveX client
you create in LabWindows/CVI.

National Instruments Corporation

3-9

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-1

OBJECTIVE

Time to complete: 20 min.

To create a 3D graph using ActiveX

LabWindows/CVI Basics II Course Manual

3-10

ni.com

Lesson 3

Exercise 3-1
Objective:

Interapplication Communication and ActiveX Automation

Using ActiveX Objects

To learn how to make powerful applications using ActiveX objects.


This exercise uses an ActiveX container to embed the National Instruments
Measurement Studio 3D Graph Control.

1. Load the 3DGraph.prj file located in the directory C:\Exercises\


CVI Basics II\Lesson 3\3DGraph.prj.
2. Run the example and try changing the graph settings and the graph style.
Click Quit when you finish.
3. Open the 3DGraph.c file and look at the code associated with
the 3D Graph ActiveX control. Look at the call to
GetObjHandleFromActiveXCtrl. This function gets a handle that
is used to reference the ActiveX control. The functions that start with
CW3DGraphLib are located in the National Instruments CW 3D
Graph 6.0 library.
4. To access the CW3DGraph functions, select InstrumentsNational
Instruments CW 3D Graph 6.0 from the Library Tree. Notice how this
instrument driver is structured in the same way as other libraries in the
Library Tree.

National Instruments Corporation

3-11

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

5. Open 3DGraph.uir. Double-click the 3D Graph control to open the


Edit ActiveX Control dialog box. You can use the Edit ActiveX Control
dialog box to edit the features of an ActiveX control.

End of Exercise 3-1

LabWindows/CVI Basics II Course Manual

3-12

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

ActiveX Automation
With ActiveX Automation, you can
Create applications that expose objects (automation
servers)
Create and control objects exposed in an automation
server application from another application (automation
clients)

An automation object can have


Methods: Functions that perform an action on an object
Properties: Information about the state of an object

ActiveX Automation
In ActiveX Automation, one application acts as the server, and the other application acts as a client.
The server exposes methods (actions) and properties (data) that a client can control and change.
For example, a spreadsheet application can be an automation server. An automation server might
expose objects, such as charts, ranges of cells, and so on, with methods to get and set these objects
properties. An automation client creates and controls objects exposed by the server application. For
example, a LabWindows/CVI program can launch Excel and open existing spreadsheets.
A class defines the type of properties and methods contained in an object. An ActiveX Automation
object is an instance of a class that exposes properties, methods, and events to ActiveX clients. An
automation object can have both methods and properties. For example, the methods of a Windows
object are actions, such as restore, minimize, and maximize, which you can perform using a
Windows control menu. The properties, such as height and width, describe the appearance of the
window.

National Instruments Corporation

3-13

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

LabWindows/CVI As an Automation Client


LabWindows/CVI Client

Creates object instance


Gets an existing object
Gets or sets properties
Invokes methods

Dispatches
action and sets
properties

Gets properties

Automation Server

Type Library

Defines and exposes


automation objects

Describes servers objects


to the automation clients

LabWindows/CVI as an Automation Client


LabWindows/CVI allows users to create applications that function as automation clients. These
applications access the exposed objects of automation servers to get and set the properties of those
objects and invoke their methods.
The figure above illustrates how a LabWindows/CVI application, acting as an ActiveX Automation
client, interacts with server applications. LabWindows/CVI accesses the servers type library to
obtain information about the servers objects, methods, and properties. LabWindows/CVI
applications can perform actions such as invoking methods, getting or setting properties, and so on.

LabWindows/CVI Basics II Course Manual

3-14

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Creating Automation Clients


Use the ToolsCreate ActiveX Controller
command to create an instrument that
communicates with the server application
Write the client application using
General LabWindows/CVI functions
Functions that the instrument provides
Functions in the ActiveX Library

Creating Automation Clients


LabWindows/CVI includes the ActiveX Controller Wizard, which guides you through the process
of creating an automation client. To access the wizard, select ToolsCreate ActiveX Controller.
The wizard creates a LabWindows/CVI instrument driver containing functions to instantiate the
server objects, reference existing server objects, get/set the objects properties, and call the objects
methods. When launched, the wizard shows a list of all the automation servers registered on your
system. When you choose the server you want to communicate with, the wizard reads the
information from that servers type library and shows all the objects, methods, and properties
exposed by that server. The wizard also shows the declarations for the functions that it creates to
interface with these objects, get/set their properties, and call their methods. When you choose the
objects that you want to communicate with, the wizard generates the appropriate functions,
provides you with the source code for those functions, and generates an instrument containing these
functions.
You can use these functions along with the LabWindows/CVI ActiveX Library and other functions
to create your client application.

National Instruments Corporation

3-15

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

LabWindows/CVI ActiveX Controller Wizard


Object library browser
Object types
Methods and properties
Long names
Created functions
Help

LabWindows/CVI ActiveX Controller Wizard


When you launch the wizard, it looks for all the registered automation servers on your system and
displays them. After you select a server, the wizard reads the type library for that server and
displays the exposed objects, their methods, and properties in the ActiveX Controller Advanced
Options dialog box.
The Instrument Prefix pull-down menu shows the name that the wizard affixes as a prefix to
all functions generated in the instrument. You can change the prefix.
If help is available for the server, a Help button appears next to the Instrument Prefix
pull-down menu. Click the Help button to launch a Windows help file for the server.
The Objects box shows all the objects exposed by the server. The objects with an underscore
preceding their names are top-level objects, objects that can be created. The other objects can
be created only by calling the methods of an existing top-level object.
All functions related to a particular object are prefixed by the name in the Object Tag box.
When you select an object, you can view the methods and properties of that object in the
Methods/Properties of _objectname browser.
Help buttons for the objects, methods, and properties link and display the associated Windows
help file.
The Function Prototype box displays the declaration of the function that is created to call the
selected method.
The wizard also generates functions to get/set all the server properties. For each top-level object,
the wizard generates functions to create and/or reference the server properties. The wizard
generates a source file containing the definitions of the functions, compiles the source file into an
object module, and creates a header file that contains the function declarations and an instrument
(.fp file) that provides function panels for these functions.
LabWindows/CVI Basics II Course Manual

3-16

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Wizard-Generated and ActiveX Functions


Top-level objects and other objects
Getting and setting properties
Automation data types and related library functions
Error handling
Low-level functions

Wizard-Generated Functions
The instrument functions that the wizard creates contain calls to the functions in the
LabWindows/CVI ActiveX Library with appropriate arguments based on the information in the
type library of the automation server. For each top-level object, the wizard generates the necessary
functionsNew to create a new object, Open to open an object from a file, and Active to get a
handle to an existing object. The other objects are created by calling the methods of top-level
objects. At least one top-level object must be initially created/referenced in the client object. Use
the GetProperty, SetProperty, and SetPropertyByRef functions to get/set the server
properties. To create the client application, use the functions that the wizard generates in
combination with other LabWindows/CVI functions, especially those in the LabWindows/CVI
ActiveX Library.

ActiveX Functions
ActiveX Automation uses specially defined data types to handle data so that the data is compatible
with different programming environments. These data types are different from the ANSI C data
types. The LabWindows/CVI ActiveX Library provides functions to convert between the two kinds
of data types. The ActiveX Library also contains functions to handle the error information, if any,
returned by the automation server. The ActiveX Library contains low-level functions that you can
use instead of the wizard-generated functions or for special circumstances.

National Instruments Corporation

3-17

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Automation Data Types


Data is transmitted in special data types between
automation clients and servers
These data types are VARIANT, SAFEARRAY,
BSTR

The LabWindows/CVI ActiveX Library contains


functions for converting between these and ANSI C
data types
Usually, the wizard-generated functions accept
C data types and internally convert them for you
Automation Data Types
Because automation clients and servers can be written in a number of programming languages, it
is necessary to use consistent data types when transferring data between clients and servers.
Automation defines three special data types:

VARIANTCan contain any other automation data type. Basically, a VARIANT is a union of all

other data types.

SAFEARRAYEquivalent to the C array, but in addition to containing the array elements, a


SAFEARRAY also contains the size of the array. If the array is multidimensional, the
SAFEARRAY contains the size of each dimension.

BSTREquivalent to the C string, but a BSTR contains the number of characters in the string,
along with the characters themselves.

When using the ActiveX Library functions or the wizard-generated functions, you might need to
send/receive data in one of the preceding data types. This action requires you to handle these data
types and convert between these data types and C data types. You can use functions in the
LabWindows/CVI ActiveX Library to perform these conversions. The library has VARIANT-related
functions, SAFEARRAY-related functions, and BSTR-related functions.
For example, to convert a C string to a BSTR, call the CA_CStringToBSTR function as follows:
status = CA_CStringToBSTR (cStr, &bStr);

LabWindows/CVI Basics II Course Manual

3-18

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Other ActiveX Library Functions


Error handling
CA_DisplayErrorInfo
CA_GetAutomationErrorString

Low-level functions
Creating, getting, and loading objects
Calling methods and properties

Freeing resources and locale functions


Other ActiveX Library Functions
The LabWindows/CVI ActiveX Library provides two functions to return error information.
CA_DisplayErrorInfo displays the description associated with an error code in a dialog box.
CA_GetAutomationErrorString converts an error code number into a meaningful error string.
The LabWindows/CVI ActiveX Library provides low-level functions that you can use to create
automation objects, get handles to existing automation objects, load automation objects from file,
invoke methods, get/set properties, and so on directly instead of using the wizard-generated
functions. The low-level ActiveX Library functions are harder to use and require knowledge of the
automation details of the server objects, which is information that the wizard gets from the type
library of the server.
You can use other functions in the LabWindows/CVI ActiveX Library to free memory resources
and get and set locales. Sometimes, a server returns data to you in variables that it has allocated
memory for, and the client must free these memory resources. In such cases, use the functions in
the Resource Management class of the ActiveX Library. Locales refer to the language used by the
server. You can get/set the locale if necessary.

National Instruments Corporation

3-19

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-2

OBJECTIVE

Time to complete: 20 min.

To control an ActiveX server on a panel with an


ActiveX container

LabWindows/CVI Basics II Course Manual

3-20

ni.com

Lesson 3

Exercise 3-2
Objective:

Interapplication Communication and ActiveX Automation

Using an ActiveX Server

To learn to control an ActiveX server on a panel with an ActiveX container.


In this exercise, you will create an application that controls the Windows
Media Player inside a LabWindows/CVI user interface. This exercise will
load an MPEG movie to be played inside Windows Media Player. This
exercise could be applied to applications where it is necessary to show a
short movie, or play a sound file to produce more interactive user interfaces.
You can apply these steps to any ActiveX server that you might want to
embed into an application.
1. Load container.prj located in the directory C:\Exercises\CVI
Basics II\Lesson 3\container.prj.
2. Open the user interface container.uir.
3. The user interface contains Windows Media Player as an ActiveX
control. In the following steps, you will build a user interface that
contains an ActiveX control, a Play Movie button, a Which Player?
button to load information about the media player, and a Quit button, as
shown in the following figure.

You can load an ActiveX control on the panel by right-clicking the panel and
selecting ActiveX. Then, select the ActiveX object from the Select ActiveX Object
dialog box and click OK.
Note

a. Double-click the Windows Media Player container to open the Edit


ActiveX Control dialog box. All ActiveX properties can be
manipulated in this dialog box. Make the Constant Name of the
control MEDIAPLAYER and the Label Media Player. You can turn
off the controls that are displayed on the Media Player by scrolling
through the properties list. For now, set ShowControls to False.
Notice that the Quick Edit Window shows how the object will

National Instruments Corporation

3-21

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

appear without the controls. Click OK to exit the Edit ActiveX


Control dialog box.
b. Add three command buttons and complete the Edit Command
Button dialog box as indicated in the following table.
Button Name
Constant Name
Callback Function
Control Mode
Label

PLAY

WHICHPLAYER

QUIT

playMovie

whichPlayer

quit

Hot

Hot

Hot

__Play Movie

__Which Player?

__Quit

You can use EditCopy and Paste to create the second and third buttons. Resize
a button by dragging its corner.
Note

c. Save the user interface file.


d. Generate the code for the user interface by selecting Code
GenerateAll Code.
e. Complete the Generate All Code dialog box as shown in the
following figure and click OK.

LabWindows/CVI Basics II Course Manual

3-22

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

When you click OK, LabWindows/CVI launches the ActiveX


Controller Wizard. Use the ActiveX Controller Wizard to create an
instrument driver for the ActiveX server. Click Compatibility
Options. Set Property Access Functions to be Per Property and
click OK. Click Next until the instrument driver is created. Finally,
click the Close button.
f. LabWindows/CVI generates the file container.c. In the main
function before the panel is displayed, it is necessary to get the
object handle from the ActiveX control on the panel. From the
Library Tree, select User Interface Library
Controls/Graphs/Strip ChartsActiveX Controls
GetObjHandleFromActiveXCtrl. Complete the function panel as
shown in the following table and insert the function call.
Panel Handle
Control ID

National Instruments Corporation

panelHandle
PANEL_MEDIAPLAYER

3-23

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Panel Handle
Object Handle

panelHandle
&playerHandle

Declare playerHandle as a static global variable of type


CAObjHandle at the top of container.c.

g. Clicking the Play Movie button prompts the user for an MPEG file
to be played in the Windows Media Player. The following
instructions show you how to add the code for the playMovie
callback function. The final playMovie callback function appears
as the following code.

The first function asks the user for a path to a file that will be
displayed in the Windows Media Player. Place your cursor inside the
playmovie callback function. From the Library Tree, select User
Interface LibraryPop-up PanelsFile/Directory Popups
FileSelectPopup. Complete the function panel as shown in the
following table and insert the function call.

LabWindows/CVI Basics II Course Manual

3-24

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Default Directory
Default File Spec
File Type List
Title

Button Label
Restrict Directory?
Restrict Extension?
Allow Cancel?
Allow Make Directory?
Path Name
Selection Status

load
no
no
yes
no

*.mpg

Select a MPEG
movie

path

Declare the path variable within the playMovie function as a


character string with length MAX_PATHNAME_LEN.
From the Library Tree, select InstrumentsWindows Media
PlayerIMediaPlayer2IMediaPlayer2SetFileName. Complete
the function panel as shown in the following table and insert the
function call.
Object Handle
Error Info
Pbstr File Name

playerHandle
NULL
path

h. Pressing the Which Player? button opens the About dialog box for
the Windows Media Player. The following instructions show you
how to add the code for the whichPlayer callback function.
The final whichPlayer callback function appears in the following
code.

National Instruments Corporation

3-25

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Place your cursor inside the whichPlayer callback function. From


the Library Tree, select InstrumentsWindows Media Player
IMediaPlayer2IMediaPlayer2AboutBox and complete the
function panel as shown in the following table and insert the function
call.
Object Handle
Error Info

playerHandle
NULL

i. Clicking the Quit button discards the ActiveX object handle and
closes the application. Place your cursor inside the quit callback
function. From the Library Tree, select ActiveX LibraryResource
ManagementDiscardObjHandle to open the
CA_DiscardObjHandle function. Pass playerHandle to
the function.
j. Save and run the program. If prompted to add necessary include
statements to the top of the file, select Yes.
Note Newer versions of Windows Media Player may have different ActiveX methods
and properties.

End of Exercise 3-2

LabWindows/CVI Basics II Course Manual

3-26

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-3

OBJECTIVE

Time to complete: 15 min.

To create a LabWindows/CVI ActiveX client


application that controls Microsoft Internet Explorer

National Instruments Corporation

3-27

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-3
Objective:

Creating an ActiveX Client Application

To create a LabWindows/CVI ActiveX client application that controls Microsoft


Internet Explorer.
In this exercise, you will create an ActiveX client that launches Microsoft
Internet Explorer, loads a Web page in the browser, and closes the browser
all through a LabWindows/CVI application. This exercise shows the power
of ActiveX technologies. In the Web browser, an ActiveX client displays the
data that is acquired or processed in LabWindows/CVI.

1. Open IE.prj located in the directory C:\Exercises\CVI


Basics II\Lesson 3\IE.prj.
2. The GUI and the skeleton code have been built for you. Open IE.uir
and study the controls. IE.c contains the skeleton code generated using
CodeBuilder.
3. First, create an instrument driver for the Internet Explorer ActiveX
server.
a. Select ToolsCreate ActiveX Controller to open the ActiveX
Controller Wizard screen, which you use to generate an instrument
driver for an ActiveX server.
b. Click Next. The wizard searches for all registered ActiveX servers
on your computer. Select Microsoft Internet Controls from the list
as shown in the following figure. Click Next.

LabWindows/CVI Basics II Course Manual

3-28

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

c. On the ActiveX Controller Wizard Configure panel, leave the


Instrument Prefix as SHDocVw. To create internet.fp, set
Target .fp File to C:\Exercises\CVI Basics II\Lesson 3\
internet.fp. Make sure that the Add .fp File To Project option
is enabled.
d. Click the Compatibility Options button. Set Property Access
Functions to Per Server. Selecting the Per Server option generates
a single GetProperty and SetProperty function through which
all get and set properties are accessed for the server. Click OK.
e. Select As automation server objects for How will you be using
ActiveX controls and document objects from this server?. This
option determines whether the object creation functions support the
placement of controls and document objects on panels.
f. Click Next.
g. On the ActiveX Controller Wizard Advanced Options panel, click
the Advanced Options button. The ActiveX Controller Advanced
Options dialog box allows you to select the objects to generate in the
type library.

National Instruments Corporation

3-29

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

h. Deselect all objects except IWebBrowser2. Your screen will look


like the following figure.

i. Click OK. Then click Next. The ActiveX Controller Wizard


generates only the methods needed for this application.
j. The instrument driver has been created for accessing the Internet
Explorer ActiveX server. Close the ActiveX Controller Wizard.
4. Clicking the Launch button opens Internet Explorer. Complete the
following instructions to add code for the Launch callback function.
The following figure shows the final Launch callback function.

LabWindows/CVI Basics II Course Manual

3-30

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

a. Open the IE.c. Place your cursor in the Launch callback function.
b. Use InternetExplorerIWebBrowser2 to create a new Internet
Explorer browser object and obtain a handle to the object. Select
InstrumentsMicrosoft Internet ControlsIWebBrowser2New
InternetExplorerIWebBrowser2 from the Library Tree. Complete
the function panel as shown in the following table and insert the
function call.
Server

NULL

Support Multithreading

Locale
Reserved
Object Handle

LOCALE_NEUTRAL
0
&IEHandle

Declare IEHandle, which is a CAObjHandle, at the top of IE.c,


as follows: static CAObjHandle IEHandle;
c. Use the SHDocVwSetProperty function to make the newly
allocated Internet Explorer browser visible. Place your cursor below
the NewInternetExplorerIWebBrowser2 function and select
InstrumentsMicrosoft Internet ControlsSetProperty from the
Library Tree. Complete the function panel as shown in the following
table and insert the function call.

National Instruments Corporation

Object Handle
Error Info

IEHandle

Property ID
Property Type
Value

Visible
CAVT_BOOL

&error

VTRUE

3-31

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Enter the static ERRORINFO error; variable in the Launch


callback function.
5. Clicking the Load Web Page button prompts the user to select an
HTML file. Complete the following instructions to add the code for the
Load callback function. The following figure shows the final Load
callback function.

a. The first function asks the user for a path to a file to display in the
Web browser. Place your cursor in the Load callback function.
Select User Interface LibraryPop-up PanelsFile/Directory
PopupsFileSelectPopup from the Library Tree. Complete the
function panel as shown in the following table and insert the function
call.
Default Directory
Default File Spec
File Type List
Title
Button Label
Restrict Directory?
Restrict Extension?
Allow Cancel?
Allow Make Directory?
Path Name

""
"*.html"
""
"Select a Web Page"

load
No
No
Yes
No
path

Selection Status

LabWindows/CVI Basics II Course Manual

3-32

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Enter char path [MAX_PATHNAME_LEN]; in the Load callback


function.
b. Add a function to convert the path returned from
FileSelectPopup into a VARIANT that can understand by the
ActiveX server. A CA_VariantSetCString converts a string to a
VARIANT. Place your cursor below the FileSelectPopup
function and select ActiveX LibraryVariant Related Functions
Assigning Values to VariantsVariantSetCString from the
Library Tree. Complete the function panel as shown in the following
table and insert the function call.
Variant

&pathToVariant

Value

path

Enter the VARIANT pathToVariant; variable within the Load


callback function.
c. After determining the path to the file and converting the path to a
VARIANT, you can pass the path to the ActiveX server to navigate to
that location. Place your cursor below the VariantSetCString
function and select InstrumentsMicrosoft Internet Controls
IWebBrowser2IWebBrowser2Navigate2 from the Library Tree.
Complete the function panel as shown in the following table and
insert the function call.
Object Handle
Error Info
URL
Flags
Target Frame Name
Post Data
Headers

IEHandle
&error
pathToVariant
CA_DEFAULT_VAL
CA_DEFAULT_VAL
CA_DEFAULT_VAL
CA_DEFAULT_VAL

Declare error as a ERRORINFO variable within the Load function.


6. Clicking the Back button loads the previous Web page (if any). Place
your cursor within the Back callback function and select Instruments
Microsoft Internet ControlsIWebBrowser2
IWebBrowser2GoBack from the Library Tree. Now, enter IEHandle
as the Object Handle and insert the function.
Remember that it is always a good practice to discard any ActiveX objects that
have been created in a program to reduce the potential of any memory leaks in your
application.
Note

National Instruments Corporation

3-33

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Tip

Set IEHandle as a parameter for the Object Handle for steps 7 and 8.
7. Clicking the Close button closes and exits the browser application
without quitting the program.
a. Use the SHDocVw_IWebBrowser2Quit function, located in
InstrumentsMicrosoft Internet ControlsIWebBrowser2
IWebBrowser2Quit, to create this functionality.
b. It is very important to discard the object handle using the
CA_DiscardObjHandle function. You can access this function by
selecting ActiveX LibraryResource Management
DiscardObjHandle from the Library Tree. After you discard the
object handle, set IEHandle to 0.
8. Clicking the Quit button closes the program. If the browser application
is still running, close the application and discard the handle before
quitting the program. Include an if condition by selecting EditInsert
ConstructIf. Insert IEHandle!=0 in the Condition field of the If
dialog box.
.

Tip You can determine if the browser is still running by checking if IEHandle is not
set to 0. Remember that it is necessary to explicitly set IEHandle to 0 when the handle
has been discarded.

9. Save the program. If prompted to add a necessary include statement,


click Yes.
10. Open the program and load ieExercise.html from the
C:\Exercises\CVI Basics II\Lesson 3 directory. Make sure
everything works as expected.

End of Exercise 3-3

LabWindows/CVI Basics II Course Manual

3-34

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

LabWindows/CVI as an Automation Server


LabWindows/CVI exposes a top-level automation
object that allows external automation clients to
control it
The Application class is creatable and contains a
number of methods to open projects, compile and
run projects, and so on
There are no other classes and no properties in the
Application class
LabWindows/CVI as an Automation Server
LabWindows/CVI is an ActiveX Automation server and can be controlled by other automation
clients. LabWindows/CVI exports one class, Application, which is a top-level, creatable class.
Application contains no properties but has a number of methods to open, build, and run projects
and contains other methods to set attributes of LabWindows/CVI and so on. The cvisrvr.fp file
contains the wizard-generated functions that interact with LabWindows/CVI using ActiveX
Automation.

National Instruments Corporation

3-35

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Creating ActiveX Servers


Use the ActiveX Server Wizard
Read Building ActiveX Servers in LabWindows/CVI

Creating ActiveX Servers


LabWindows/CVI includes a wizard that simplifies the process of creating an automation server.
Select ToolsCreate ActiveX Server to access this wizard. The wizard walks you through
choosing files that support your LabWindows/CVI ActiveX server.
You can make ActiveX servers as complex as the application requires. For more specific
information about creating a LabWindows/CVI ActiveX server, refer to Building ActiveX Servers
in LabWindows/CVI. You can find this document in C:\Program Files\National
Instruments\CVI\bin. You also can access this document by clicking the Help button in any
panel of the wizard and then clicking the link to the document in the help topic that appears.

LabWindows/CVI Basics II Course Manual

3-36

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Editing ActiveX Servers

Create and modify objects and interfaces in your ActiveX server


Part of the initial server creation process
Can update server settings anytime

Editing ActiveX Servers


After you create the skeleton of your ActiveX server, LabWindows/CVI opens the Edit ActiveX
Server tool. You can use the Edit ActiveX Server tool to create and modify objects and interfaces
in your ActiveX server. The tool includes options to edit interfaces, objects, and server settings.
After you finalize your ActiveX server settings, the wizard generates the functions and provides
you with the source code to run your ActiveX server.
You can use the Edit ActiveX Server feature at any time to add, remove, or update interfaces,
objects, and server settings. To access the Edit ActiveX Server feature at any time other than during
initial server creation, select ToolsEdit ActiveX Server.
Now you can use these functions and settings along with the LabWindows/CVI ActiveX Library
and other functions to create and use your ActiveX server.

National Instruments Corporation

3-37

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-4

OBJECTIVE

Time to complete: 20 min.

To run an ActiveX Server

LabWindows/CVI Basics II Course Manual

3-38

ni.com

Lesson 3

Exercise 3-4
Objective:

Interapplication Communication and ActiveX Automation

Running an ActiveX Server

To run an ActiveX server.


1. Load simpleEXE.prj located in the directory C:\Exercises\CVI
Basics II\Lesson 3\simpleEXE.prj. This example is already
written and demonstrates how to use an ActiveX server and ActiveX
client created in LabWindows/CVI.
2. Select FileSet Active ProjectSimpleEXE. This makes
SimpleExe.prj active.
3. To compile and build an executable with debugging information, create
an executable in debug mode by selecting BuildConfiguration
Debug.
4. Select BuildCreate Debuggable Executable. When you create a
debuggable executable, the ActiveX server is registered on your system.
5. Select FileSet Active ProjectSimpleEXEClient to make
SimpleEXEClient.prj active.
6. Compile and run the project. The client window appears as shown in the
following figure.

7. Click the Launch Server button to launch the server and enable the
Server Visibility option to see the server.
8. Manipulate the controls on the server application to see the server
functionality. Quit and close the server client when you finish.
Note simpleEXE.prj creates and registers an ActiveX server with the name
simpleEXE. This server can be called from any ActiveX client application, which can

be created with LabVIEW, Microsoft Visual Basic, Visual C++, and other compatible
compilers.

End of Exercise 3-4

National Instruments Corporation

3-39

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

DataSocket Technology

DataSocket Technology
Many instrumentation solutions involve a single local application for acquisition, logging, analysis,
and presentation. However, because of the rise in popularity of the Internet and company Intranets
and the need to monitor and control your data acquisition remotely, you often need to exchange live
data with other applications on different computers around the world. DataSocket simplifies live
data exchange between different applications on one computer or between computers connected
through a network.
A variety of different technologies, including TCP/IP and Dynamic Data Exchange (DDE), exist
today to share data between applications, but most of these tools are not targeted for live data
transfer to multiple clients. With TCP/IP, you must convert your data into an unstructured stream
of bytes in the broadcasting application and then parse the stream of bytes back into its original
format in subscribing applications. DataSocket, however, simplifies live data transfer. DataSocket
implements an easy-to-use, high-performance programming interface designed specifically to
share and publish live data in measurement and automation applications. In addition, DataSocket
features interapplication connectivity, rich data types, and security to make sharing data easy.

LabWindows/CVI Basics II Course Manual

3-40

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

DataSocket Features
Live data transfer
Multiple clients
One high-level API for different source types
Avoids the burden of parsing
DataSocket Server manages networking
URL to specify connection

DataSocket Features
DataSocket is a single, unified, end-user Application Programming Interface (API) for connecting
to data from a number of sourceslocal files, files on FTP or Web servers, and data items on OPC
servers. To specify data locations, a DataSocket application uses a familiar networking standard,
the URL. Just as a Web browser uses a URL to connect to a Web page, a DataSocket application
uses a URL to connect to data. By using an industry-standard URL, you can quickly bring data into
or share data from your DataSocket applications. In addition, the DataSocket Transfer Protocol
connects a DataSocket application to live data by specifying a connection to a DataSocket Server.
The DataSocket Server, a lightweight, stand-alone component, manages most of the networking
tasks for you.
With the DataSocket Server programs using DataSocket, you can broadcast live measurement data
at high rates across the Internet to multiple remote clients concurrently. These client applications
use DataSocket to subscribe to the live measurement data. Because the DataSocket Server is a
stand-alone component, it simplifies network (TCP/IP) programming by automatically managing
connections to clients and automatically converting your measurement data to and from the stream
of bytes sent across the network. You do not need to write the parsing code. The DataSocket Server
can run on any machine on your network, which improves performance and provides security by
isolating the Web connections from your acquisition application.

National Instruments Corporation

3-41

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Data Entities and Attributes

Different data entities

Local files: file:<file-path>


FTP server: ftp://<host>/<path>
Web server: http://<host>/<path>
DataSocket server: dstp://<host>/<path>
OPC server: opc:/<server>/<item>

Data attributes
Transfer data properties
Can be easily configured/modified
Avoids user parsing

Interapplication connectivity
Security
Use DataSocket Server Manager to manage security privileges

Data Entities and Attributes


In many cases, your applications need to exchange complicated data. In addition to publishing a
waveform, you might want to publish the waveforms timestamp, quality, or sample rate.
DataSocket accomplishes this task with data attributes. Attributes are bound to the data, so no extra
connection is needed. However, attributes do not affect the fundamental type of the data. You can
add new attributes without breaking the existing application.
Because DataSocket is a technology that is implemented as an NI Measurement Studio ActiveX
control and as a LabWindows/CVI library, your LabWindows/CVI applications, LabVIEW VIs,
Web pages, Microsoft Visual Basic applications, and Excel spreadsheets can all exchange live data
with the same API. Your applications can share live data with Web pages and applications written
in other development environments.
The DataSocket Server provides security using the DataSocket Server Manager. With the
DataSocket Server Manager, you can specify which machines have the right to read, write, and
create particular data items on a DataSocket Server.

LabWindows/CVI Basics II Course Manual

3-42

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

DataSocket API

Main functions

DS_Open
DS_OpenEx
DS_DiscardObjHandle
DS_GetDataType
DS_GetDataValue
DS_Update
DS_SelectURL
DS_FreeMemory
DS_GetLibraryErrorString

Attribute functions
Status functions
Local Server Control function
DS_ControlLocalServer

Polling Queue functions

DataSocket API
The DataSocket API contains the following functions:

Main functionsFunctions that open and discard handles to connections, get/set data values,
browse and select URLs, free resources, and update the connection. These are the functions you
need for most applications.

Attribute functionsFunctions that you use to work with data attributes. Use these functions
when you associate attributes, such as time-stamping data, information about physical units,
and so on.

Status functionsFunctions that provide status information about the DataSocket connection.

Local Server Control functionDS_ControlLocalServer. Programmatically launch,


display, hide, and close the DataSocket Server on the local machine.

Polling Queue functionsFunctions that you use to get and set properties of DataSocket
polling queues. Currently, only the DataSocket Transfer Protocol (DSTP) supports polling.

National Instruments Corporation

3-43

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Structure of a Data Writer


Open connection to data target
File, Web server, FTP server, data server

Prepare data to be written


Transfer data to the data target
This step can be automated so that when the data
changes, the new data is automatically transferred to the
target: LIVE CONNECTION

Close connection to data target


Structure of a Data Writer
To create a program to write to a DataSocket target, complete the following steps:
1. Open a connection and obtain a handle to the data target using DS_OpenEx. You must specify
whether to configure the DataSocket object for manual or automatic updating.
2. Formulate the data to be written.
3. Write the data to the target using DS_SetDataValue. If you configure the DataSocket object
for automatic updating, setting the data value on the client program updates the value on the
target. If you configure the DataSocket object for manual updating, call DS_Update to update
the target with the new value after writing it using DS_SetDataValue.
4. After communication, call DS_DiscardObjHandle to close the connection and discard the
handle.

LabWindows/CVI Basics II Course Manual

3-44

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Structure of a Data Reader


Open connection to data source
File, Web server, FTP server, data server

Read data from data source


This step can be automated so that whenever the data in
the source changes, the new data is automatically
transferred to the application: LIVE CONNECTION

Process and display data


Close connection to data source
Structure of a Data Reader
To create a program to read from a DataSocket connection, complete the following steps:
1. Open a connection and get a handle to the data source using DS_OpenEx. You must specify
whether to configure the DataSocket object for manual or automatic updating.
2. Read the data from the source using DS_GetDataValue. If you configure the DataSocket
object for automatic updating, the callback function is called when the data changes on the data
source. You then must call DS_GetDataValue to read the data. If you configure the
DataSocket object for manual updating, there is no callback function. Instead, you must call
DS_Update before reading the data with DS_GetDataValue.
3. Process the data and display it according to your requirements.
4. Close the connection and discard the handle using DS_DiscardObjHandle.

National Instruments Corporation

3-45

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-5

OBJECTIVE

Time to complete: 30 min.

To create DataSocket writer and reader


applications to write/read a DSTP data entity

LabWindows/CVI Basics II Course Manual

3-46

ni.com

Lesson 3

Exercise 3-5
Objective:

Interapplication Communication and ActiveX Automation

Creating DataSocket Writer and Reader


Applications

To create DataSocket Writer and Reader applications to write/read a DSTP


data entity.

Part A: DataSocket Writer


1. Open dsWriter.prj located in the directory C:\Exercises\CVI
Basics II\Lesson 3\dsWriter.prj. This project writes a
double value to the DataSocket Server whenever the value of the
variable changes in the application.
2. The GUI and part of the source code are already built for you. Open
the .uir file and examine the panel.
3. Open dsWrite.c. When you click the CONNECT button, the
application establishes a connection to a dstp:// data target on the
local host (for example, dstp://localhost/value). Add code to
the connectCB callback function to perform this action by calling the
DS_OpenEx function. From the Library Tree, select DataSocket
LibraryOpenEx and complete the function panel as shown in the
following table.
URL
Access Mode
Event Function
Callback Data
Execution Model
Timeout
DS Handle

dstp://localhost/value

DSConst_WriteAutoUpdate
NULL
NULL

Event Model
DSConst_Asynchronous
&dsHandle

Declare dsHandle as a global DSHandle variable to use for the


DataSocket handle.
4. When you click the DISCONNECT button, the application disconnects
from the DSTP target. Create this functionality by adding the
DS_DiscardObjHandle function to the disconnectCB callback
function. Select DataSocket LibraryDiscardObjHandle and enter
dsHandle as the DS Handle parameter. Insert the function call when
you are done.
5. When you change the value of the Writer control, the application sends
a COMMIT event to the valueCB function. When this event occurs, get
the value from the numeric control by adding the GetCtrlVal function
to the valueCB callback function. From the Library Tree, select User
Interface LibraryControls/Graphs/Strip ChartsGeneral

National Instruments Corporation

3-47

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

FunctionsGetCtrlVal. Complete the function panel as shown in the


following table and insert the function call into your source code. The
variable value has already been declared to store the value from the
numeric control.
Panel Handle

panelHandle

Control ID
Value

PANEL_VALUE
&value

6. Pass value to DS_SetDataValue to update the value on the


DataSocket server. Select DataSocket LibrarySetDataValue and
complete the function panel as shown in the following table.
DS Handle
Type
Value
Dimension 1
Dimension 2

dsHandle

double
&value
0
0

7. Start the DataSocket server by selecting StartAll ProgramsNational


InstrumentsDataSocketDataSocket Server.
8. Build and run the project. When you click the CONNECT button, the
number of connections on the DataSocket server increments by 1, and
when you click the DISCONNECT button, the number decrements by
1 (if greater than zero).
9. Create a release executable of this project, and name it dsWriter.exe.
To create the release executable, select BuildConfigurationRelease
and then select BuildCreate Release Executable.

Part B: DataSocket Reader


The objective of this part of the exercise is to create an application that reads
the double value from the DataSocket Server whenever the value of the
variable changes.
1. Open dsReader.prj located in the directory C:\Exercises\CVI
Basics II\Lesson 3\dsReader.prj.
2. The GUI and part of the source code are already built for you. Examine
the .uir and the source file.
3. When you click the CONNECT button, the application establishes
a connection to the dstp:// data source on the local host (for example,
dstp://localhost/value). Add DS_OpenEx to the connectCB
callback function to perform this action. From the Library Tree, select

LabWindows/CVI Basics II Course Manual

3-48

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

DataSocket LibraryOpenEx and complete the function panel as


shown in the following table.
URL
Access Mode
Event Function
Callback Data
Execution Model
Timeout
DS Handle

dstp://localhost/value

DSConst_ReadAutoUpdate
DataSocketEvent
NULL

Event Model
DSConst_Asynchronous
&dsHandle

Declare dsHandle as a global DSHandle variable to use for the


DataSocket handle.
4. Create a DataSocketEvent function. You must write this function to
handle the events from the DataSocket connection. First insert the
following function prototype at the top of the file below the global
variables.
void DataSocketEvent (DSHandle dsHandle, int event,
void *CallbackData);

At the bottom of the file, create the function shown in the following
figure. You will complete the code for this function later in this exercise.

a. When the value of the data source changes, the DataSocket


callback function (DataSocketEvent) is called with the
DS_EVENT_DATAUPDATED event. Insert a switch statement in the
DataSocketEvent callback to handle this event, as shown in the
previous figure.
b. To retrieve the value on the DataSocket server, insert
DS_GetDataValue. From the Library Tree, select DataSocket
LibraryGetDataValue and complete the function panel as shown
in the following table.

National Instruments Corporation

3-49

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

DS Handle
Type
Value
Size
Dimension 1
Dimension 2

dsHandle

double
&value
sizeof(double)
NULL
NULL

Declare the variable value as type double in the function


DataSocketEvent.
c. Display the value in the Reader control on the GUI. From the
Library Tree, select User Interface Library
Controls/Graphs/Strip ChartsGeneral FunctionsSetCtrlVal.
Complete the function panel as shown in the following table and
insert the function call into your source code.
Panel Handle
Control ID
Value

panelHandle
PANEL_VALUE
value

5. When you click the DISCONNECT button, the application disconnects


from the DSTP target. Call DS_DiscardObjHandle in the
disconnectCB callback function to perform this action. Select
DataSocket LibraryDiscardObjHandle and enter dsHandle as the
DS Handle parameter.
6. Run the DataSocket server and the dsWriter.exe applications if they
are not running. Connect the server to the dsWriter application. Now
build and run the dsReader.prj project and connect to the server. The
number of connections on the DataSocket Server increments by 1. Now
change the value of the Writer control on the DATASOCKET WRITER
panel. The value displayed on the DATASOCKET READER panel
updates to show the current value.
7. (Challenge) If you click the DISCONNECT button more than once, you
receive an error. Develop error handling code to prevent the application
from crashing.
When you click CONNECT or DISCONNECT, the callback function that
responds to the event you generate creates or discards DataSocket object, respectively. If
you click CONNECT or DISCONNECT repeatedly, you will change the number of
connections on DataSocket Server only once because the callback function always refer
to the same DataSocket object.
Note

End of Exercise 3-5

LabWindows/CVI Basics II Course Manual

3-50

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

DataSocket Binding
Codeless DataSocket communication
Available with:

Numeric controls
Text box controls
Strip charts
Graphs
Tables
String controls

Controls can either read or write data

DataSocket Binding
LabWindows/CVI allows you to quickly publish and subscribe data on a DataSocket Server
without having to write any code. Using this feature, you can easily transfer data between
applications and platforms. DataSocket Binding is available with numeric controls, text box
controls, string controls, strip charts, graphs, and tables. To enable DataSocket Binding,
double-click the control and click the DataSocket Binding button in the Edit Control dialog box.
In the DataSocket Binding dialog box you can enable the binding, specify the location of the data,
and specify whether the control is a data publisher or subscriber.

National Instruments Corporation

3-51

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-6

OBJECTIVE

Time to complete: 30 min.

To create a DataSocket writer and reader application


that uses DataSocket binding

LabWindows/CVI Basics II Course Manual

3-52

ni.com

Lesson 3

Exercise 3-6
Objective:

Interapplication Communication and ActiveX Automation

Using DataSocket Binding

To create a DataSocket Writer and Reader application that uses DataSocket Binding.

Part A: DataSocket Writer


The objective of this part is to write an application that can publish data to
the DataSocket Server using DataSocket Binding.
1. Create a new project.
2. Save the project as C:\Exercises\CVI Basics II\
Lesson 3\DSBWriter.prj.
3. Create a new user interface file by selecting FileNewUser Interface
(*.uir).
4. Complete the following steps to build a user interface that contains a dial
and a Quit button.

a. Double-click the panel and enter DSWPANEL for the Constant Name
and DataSocket Writer for the Panel Title. Click OK.
b. Add a dial to the panel by right-clicking in the panel and selecting
NumericDial.
c. Double-click the dial to open the Edit Numeric Dial dialog box and
enter Data to Write as the Label.
d. Click the DataSocket Binding button. Select the Enable Data
Binding checkbox and complete the dialog box as shown in the
following table.
Server
Connection Type

dstp://localhost/data

Write

e. Click OK when done. Then click OK again to exit the Edit Numeric
Dial dialog box.

National Instruments Corporation

3-53

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

f. Add a command button to the panel. Double-click the command


button to open the Edit Command Button dialog box. Make the
constant name of the control QUIT, the callback function quit, and
the label __Quit.
5. Save the user interface as DSBWriter.uir.
6. Select FileAdd DSBWriter.uir to Project.
7. Select CodeGenerateAll Code.
8. In the Generate All Code dialog box, select Add to Current Project in
the Target Files section. Select quit in the Select QuitUserInterface
Callbacks section. Click OK to generate the code.
9. Create a release executable of this project and save it as
DSBWriter.exe. To create the release executable, select Build
ConfigurationRelease and select BuildTarget TypeExecutable.
Then, select BuildCreate Release Executable.

Part B: DataSocket Reader


The objective of this project is to write an application that can subscribe to
data from the DataSocket server using DataSocket Binding.
1. Create a new project.
2. Save the project as C:\Exercises\CVI Basics II\Lesson 3\
DSBReader.prj.
3. Create a new user interface file by selecting FileNewUser Interface
(*.uir).
4. Complete the following steps to build a user interface that contains a
strip chart and a Quit button.

a. Double-click the panel and enter DSRPANEL for the Constant Name
and DataSocket Reader for the Panel Title. Click OK when
done.

LabWindows/CVI Basics II Course Manual

3-54

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

b. Add a strip chart to the panel by right-clicking the panel and


selecting GraphStrip Chart.
c. Double-click the strip chart to open the Edit Strip Chart dialog box.
Make the label Data to Read.
d. Click the Y-axis button and change the Minimum to -10 and the
Maximum to 10. Click OK.
e. Click the DataSocket Binding button. Select the Enable
DataBinding checkbox and complete the dialog box as shown in
the following table.
Server
Connection Type

dstp://localhost/data

Read

f. Click OK when done. Then click OK again to exit the Edit Strip
Chart dialog box.
g. Add a command button to the panel. Double-click the command
button to open the Edit Command Button dialog box. Make the
constant name of the control QUIT, the callback function quit, and
the label __Quit. Then click OK.
5. Save the user interface as DSBReader.uir.
6. Select FileAdd DSBReader.uir to Project.
7. Select CodeGenerateAll Code.
8. In the Generate All Code dialog box, select Add to Current Project in
the Target Files section. Select quit in the Select QuitUserInterface
Callbacks section. Click OK to generate the code.
9. Create a release executable of this project and save it as
DSBReader.exe. To create the release executable, select Build
ConfigurationRelease and select BuildTarget TypeExecutable.
Select BuildCreate Release Executable.

Part C: Test
1. Run the DataSocket server if it is not running.
2. Run the DSBWriter.exe application and the DSBReader.exe
application.
3. Rotate the dial on the DataSocket Writer panel. Notice that the strip
chart plots the value of the dial when the dial value changes.

End of Exercise 3-6

National Instruments Corporation

3-55

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Using LabVIEW (Optional)


Call LabVIEW VIs from LabWindows/CVI using
ActiveX Automation and VI Server technology
Use the Create VI Reference to CVI Instrument
Drivers option in LabVIEW to call LabWindows/CVI
instrument drivers from LabVIEW

Using LabVIEW (Optional)


You can call and run LabVIEW VIs from within LabWindows/CVI using ActiveX automation. In
LabVIEW, ActiveX automation is known as VI Server technology.
LabVIEW also provides a mechanism to convert LabWindows/CVI instrument drivers into
LabVIEW instrument drivers. LabVIEW uses the LabWindows/CVI .fp file to create a set of VIs
that call the appropriate functions in the LabWindows/CVI DLL associated with the instrument
driver.

LabWindows/CVI Basics II Course Manual

3-56

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-7 (Optional)

OBJECTIVE

Time to complete: 30 min.

To use the Convert CVI .FP file utility in LabVIEW

National Instruments Corporation

3-57

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-7
Objective:

Using the CVI Function Panel Converter


(Optional)

To use the Convert CVI .FP File utility in LabVIEW to convert a LabWindows/CVI
instrument driver for use in LabVIEW.

Note This Exercise will work if LabVIEW Interface Generator for LabWindows/CVI
1.1 is installed on your computer. This installer is located in the C:\Exercises\CVI
Basics II\Lesson 3 directory. This installer creates LabVIEW VIs from instrument
drivers. You must have the following software installed before you can install and use the
LabVIEW Interface Generator for LabWindows/CVI Instrument Drivers.

Windows 2000/XP

LabVIEW 8.0 or later


1. Create a new project in LabWindows/CVI.
2. Save the project as C:\Exercises\CVI Basics II\Lesson 3\
Devsim.prj.
3. Add the files associated with the Device Simulator instrument driver:
Devsim.c, Devsim.h, and Devsim.fp. You can find these files in the
C:\Exercises\CVI Basics II\Lesson 3\ directory.
4. Select BuildTarget TypeDynamic Link Library.
5. Select BuildConfigurationRelease.
6. Select BuildTarget Settings to open the Target Settings dialog box.
Enter the name of the DLL as Devsim_32.dll and copy DLL to the
VXIplug&play directory, as shown in the following figure.

LabWindows/CVI Basics II Course Manual

3-58

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

a. Click the Change button in the Exports section.


b. In the DLL Export Options dialog box, check the Devsim.h file to
export the functions that are prototyped in that header file. Click OK
to close DLL Export Options dialog box.
c. Click OK to close the Target Settings dialog box.
7. Select BuildCreate Release Dynamic Link Library to create
the DLL.
8. Select StartAll ProgramsNational InstrumentsLabVIEW 8.0
LabVIEW and open a blank VI.
9. Select ToolsInstrumentationCreate VI Interface to CVI
Instrument Driver.
10. LabVIEW opens the LabVIEW Interface Generator for LabWindows
dialog box. Select Advance and click Next.
11. In the Function panel (.fp) file field, specify C:\Exercises\CVI
Basics II\Lesson 3\Devsim.fp using the Browse button. When
you select this .fp file, LabVIEW includes Devsim.h in Header(.h)
File field. Select LabVIEW/instr.lib for Destination Directory. Make
sure your dialog box looks like the following figure. Then click Next.

12. Select all the files in the Select the files to generate during the conversion
process panel and click Next until you reach Accept or skip help string
replacement and deletion panel. Click the Accept All and click Next.
This completes the conversion.

National Instruments Corporation

3-59

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

13. Clicking the View the Report and View VI Tree buttons displays the
report and the generated VI. When completed, click the Done button.
14. LabVIEW generates all the VIs and saves them in the destination
directory you specified in the conversion process. The default directory
is \National Instruments\LabVIEW 8.0\instr.lib\Devsim.
LabVIEW also puts the icons associated with these VIs in the
Instr.lib section of the Functions palette. You can access these VIs
by right-clicking a block diagram window and selecting Instrument
I/OInstrument DriverDevsim.
15. Open one of the generated VIs and study it. The VI uses a Call Library
Function to call the appropriate function in the Devsim_32.dll. The
following figure is the block diagram of DevSim Initialize.VI
generated by LabVIEW Interface Generator.

16. (Challenge) If your instrument simulator is correctly configured as a


GPIB simulator, create a simple VI in LabVIEW using the generated
instrument driver VI to communicate with the instrument.

End of Exercise 3-7

LabWindows/CVI Basics II Course Manual

3-60

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Controlling VIs from LabWindows/CVI Using


VI Server (Optional)
Create or open a
LabVIEW application
object (top-level)

Use NewApp or OpenApp


from the ActiveX controller

Load a VI into memory


and get a handle to it

Invoke the GetVIReference


method of the Application object

Perform an operation
on the VI

Invoke methods of the virtual


instrument object: call, run,
SetControlValue,
GetControlValue

Controlling VIs from LabWindows/CVI Using VI Server (Optional)


Calling VIs through VI Server is similar to using objects with other ActiveX servers. Essentially,
you create an ActiveX controller for LabVIEWs type library in LabWindows/CVI. Using the
ActiveX Controller Wizard-generated functions, you first create a top-level LabVIEW application
object. Then, you call the GetVIReference method of the top-level object to load the specified
VI into memory and return a handle to it. Subsequently, using this handle, you can call methods
and get/set properties of the virtual instrument object.
The following list describes the important methods you can execute on the virtual instrument
object.

CallUse this method to execute the VI as a subVI.

RunUse this method to execute the VI as a top-level VI.

GetControlValueUse this method to get the value of one of the VI controls.

SetControlValueUse this method to set the value of one of the VI controls.

Refer to the wizard-generated function panel and the LabVIEW Help files for a comprehensive
discussion of each of the other methods and properties.

National Instruments Corporation

3-61

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-8 (Optional)

OBJECTIVE

Time to complete: 25 min.

To call a LabVIEW VI from LabWindows/CVI using


VI Server

LabWindows/CVI Basics II Course Manual

3-62

ni.com

Lesson 3

Exercise 3-8
Objective:

Interapplication Communication and ActiveX Automation

Communicating with LabVIEW VIs (Optional)

To communicate with LabVIEW VIs from LabWindows/CVI using VI Server.


1. Open VIServer.prj located in the directory C:\Exercises\CVI
Basics II\Lesson 3\VIServer.prj.
2. The GUI and skeleton code are available. The GUI is shown in the
following figure.

3. Select ToolsCreate ActiveX Controller to create an ActiveX


controller instrument for the LabVIEW server.
a. In the ActiveX Controller Wizard, select the LabVIEW 8.0 Type
Library from the ActiveX Server list and click Next. Enter
LabVIEW as the Instrument Prefix and C:\Exercises\CVI
Basics II\Lesson 3\LabVIEWServer.fp as Target .fp File
to path. Enable the Add .fp File To Project option. Then click
Compatibility Options. Select Per Property for the Property
Access Function options. Click OK and then click Next.
b. On the Advanced Options panel of the ActiveX Controller Wizard,
click the Advanced Options button. The ActiveX Controller
Advanced Options dialog box allows you to select the objects to
generate in the type library.
c. Deselect all objects except Application and
VirtualInstrument. Your screen will look like the following
figure.

National Instruments Corporation

3-63

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

d. Click OK. Then click Next. The ActiveX Controller Wizard


generates only the methods needed for this application.
e. Click Next until you get a message that you have generated an
instrument driver. Then click the Close button to exit the ActiveX
Controller Wizard.
4. When the user clicks the Launch LabVIEW button, the program
launches LabVIEW. Instantiate the LabVIEW application object in the
LaunchCB callback function. From the Library Tree, select
InstrumentsLabVIEW 8.0 Type Library_ApplicationNewApp.
This function returns a handle, which you can use in the other functions,
to the LabVIEW application. Use the variable &LabviewHandle,
which has already been declared, as the Object Handle and leave the
other parameters as the defaults.
5. When the user clicks the Load VI button, the add.vi in the
Exercises folder loads. To place the VI in memory, add
AppGetVIReference function in the LoadCB callback function. From
the Library Tree, select InstrumentsLabVIEW 8.0 Type Library
_ApplicationAppGetVIReference. Complete the function panel as
shown in the following table and insert the function call.

LabWindows/CVI Basics II Course Manual

3-64

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Object Handle

LabviewHandle

Error Info
VI Path
Password
Resv For Call
Options
Return Value

NULL
pathName

VFALSE
0
&labviewVI

6. When the user clicks the Run Add button, add.vi runs, the sum is
calculated in LabVIEW and displayed in the sum control. The add.vi
has two inputs, num1 and num2, and one output, sum. add.vi adds
num1 and num2 and returns the value to sum.

a. In order to set the inputs num1 and num2 in add.vi, call the
VirtualInstrSetControlValue method. Place your cursor
after the comment. /* Set the values for the different
inputs on the VI */ in the AddRunCB callback function. From
the Library Tree, select InstrumentsLabVIEW 8.0 Type
LibraryVirtualInstrumentVirtualInstrSetControlValue and
complete the function panel as shown in the following table to set the
value of num1.
Object Handle
Error Info
Control Name
Value

labviewVI
NULL
num1
myValue1

b. To set the value of num2, call the


VirtualInstrSetControlValue method again with the

following parameters.

National Instruments Corporation

3-65

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Object Handle

labviewVI

Error Info
Control Name
Value

NULL
num2
myValue2

c. To execute the VI, call the VirtualInstrRun method and place it


below the comment /* Run the VI as a top-level VI */.
Select InstrumentsLabVIEW 8.0 Type Library
VirtualInstrumentVirtualInstrRun and complete the function
panel as shown in the following table.
Object Handle
Error Info
Async

labviewVI
NULL

VTRUE

d. To get the value of sum from the VI, call the


VirtualInstrGetControlValue method and place it below the
comment /* Get the value from the VI's output */.
From the Library Tree, select InstrumentsLabVIEW 8.0 Type
LibraryVirtualInstrumentVirtualInstrGetControlValue and
complete the function panel as shown in the following table.
Object Handle

labviewVI

Error Info
Control Name
Return Value

NULL
sum
&returnedValue

e. The VirtualInstrGetControlValue method returns a


VARIANT. It is necessary to convert the VARIANT to a double. Call
the VariantGetDouble function to convert the VARIANT return
value to a C type double. From the Library Tree, select ActiveX
LibraryVariant Related FunctionsRetrieving Values from
VariantsVariantGetDouble and complete the function panel as
shown in the following table.
Variant
Value

LabWindows/CVI Basics II Course Manual

&returnedValue
&sum

3-66

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

f. Update the sum control on the panel with SetCtrlVal. From the
Library Tree, select LibrariesUser Interface Library
Controls/Graphs/Strip ChartsGeneral FunctionSetCtrlVal
and complete the function panel as shown in the following table to
set the value of num1.
Panel Handle
Control ID
Value

panelHandle
PANEL_SUM
sum

7. When the user clicks the Call Add button, add.vi is called as a subVI.
The VirtualInstrCall method in the VirtualInstrument class is
invoked. This function has arguments for the control values so you do
not need the VirtualInstrSetControlValue and
VirtualInstrGetControlValue methods. The code for the
function has already been written for you. Study how the function calls
the VI like a C function call, where the parameters are passed by calling
the function.
8. The Unload VI button discards add.vi, and the EXIT
LabVIEW button exits LabVIEW. This action occurs with the
DiscardObjHandle function in the ActiveX Library. Unload VI
discards the VI handle, and EXIT LabVIEW discards the LabVIEW
handle. The Quit button quits the program. The code has already been
written to discard the VI and exit the program.
9. Run the program. Ensure that the correct sum returns when the VI runs,
as well as when the VI is called as a subVI.

End of Exercise 3-8

National Instruments Corporation

3-67

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Transmission Control Protocol (TCP)


A method for communicating between
simultaneously running applications over a network
128.161.15.29

155.247.207.70
TCP network

Transmission Control Protocol (Optional)


Transmission Control Protocol (TCP) is a protocol for communicating between simultaneously
running applications over the network. You can create distributed applications, taking advantage of
various resources on your network using the TCP Support Library. TCP is not limited to the
Windows platform.

LabWindows/CVI Basics II Course Manual

3-68

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

TCP Client-Server Architecture


Server

Client
Initiates and controls
the conversation

TCP-IP

Provides data and


service to client

TCP Client-Server Architecture


Network communication using the TCP Support Library involves the client-server architecture. A
TCP server can send and receive information to and from a client application through a network.
A TCP client can send and request data to and from a server application. When registered, a server
waits for clients to request connection to it. A client, however, can request connection only to an
existing server. With the LabWindows/CVI TCP Support Library, you can write programs that act
as TCP servers or clients.

National Instruments Corporation

3-69

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

TCP Servers and Clients


TCP servers can arbitrarily send data to the client
Both machines must have an IP address
When connected, communication is as easy as
reading and writing to a file
Lower-level implementation than DataSocket

TCP Servers and Clients


TCP clients and servers reside on different computers on a network. If you write a client
application, you must know the Internet Protocol (IP) address and port number of the server to
connect to, for example labwindows.natinst.com 4000 or 130.164.15.70 4000. If you
write a server application, the server must register itself on the specified host IP address and port
number.
If you write a multiple-client TCP application and you want to broadcast data from a central server,
consider the benefits of DataSocket. The TCP Support Library is a lower-level interface to network
communication as compared to DataSocket.

LabWindows/CVI Basics II Course Manual

3-70

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

TCP Callback Functions


Function like user interface callback functions
int TCPcallback (int handle, int xType,
int errCode, void *callbackData);

xType is the event that occurred


Data is not transmitted with the event
Explicit read function must be called

TCP Callback Functions


TCP servers and clients each have their own callback function. A TCP callback function has the
following format:
int TCPcallback (int handle, int xType, int errCode, void *callbackData);

handleNumber that identifies the client-server connection.

xTypeNumber that identifies a specific event for the client or server. The following table lists
the TCP transaction types that can trigger a callback function.
xType

Server Client

When?

TCP_CONNECT

when a new client requests a connection

TCP_DISCONNECT

when conversation partner quits

TCP_DATAREADY

when conversation partner sends data

errCodeIndicates if the connection terminates due to an error.

*callbackDataA pointer to user-defined data.

National Instruments Corporation

3-71

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

TCP Server/Client Functions


Server
Client

RegisterTCPServer
ConnectToTCPServer

ServerTCPWrite

ServerTCPRead

UnregisterTCPServer
UnregisterTCPServer

ClientTCPWrite

ClientTCPRead

DisconnectFromTCPServer

TCP Server/Client Functions


As shown in the figure above, TCP servers and clients follow a simple
connectread/writedisconnect procedure.
Server Functions

RegisterTCPServerRegisters your application as a valid TCP server.

UnregisterTCPServerUnregisters your application as a TCP server.

DisconnectTCPClientDisconnects a specific client from the server. This function is not


shown in the figure above.

Client Functions

ConnectToTCPServerEstablishes a conversation between your application and an

existing server.

DisconnectFromTCPServerDisconnects your application from the server.

Both

ServerTCPRead/ClientTCPReadReads data from the conversation partner.

ServerTCPWrite/ClientTCPWriteSends data to the conversation partner.

LabWindows/CVI Basics II Course Manual

3-72

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

ServerTCPRead/ClientTCPRead
TCP Event Manager

Server/Client
Sends Data

TCP_DATAREADY

Server/Client
Disconnects

TCP_DISCONNECT

Client Connects

TCP_CONNECT

Execute a ServerTCPRead/ClientTCPRead upon receiving


the TCP_DATAREADY event

ServerTCPRead/ClientTCPRead
The events that a TCP callback function recognizes are shown in the figure above. The following
code shows a typical TCP callback function.
int TCPcallback (int handle, int xType, int errCode, void *callbackData)
{
switch (xType) {
case TCP_DATAREADY:
/* handle incoming data.

use Server/ClientTCPRead*/

break;
case TCP_DISCONNECT:
/* notify user that the conversation
partner has disconnected */
break;
case TCP_CONNECT:
/* server only. notify user that a client
has connected */
break;
}
}

National Instruments Corporation

3-73

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Exercise 3-9

OBJECTIVE

Time to complete: 20 min.

To run and examine a TCP example

LabWindows/CVI Basics II Course Manual

3-74

ni.com

Lesson 3

Exercise 3-9
Objective:

Interapplication Communication and ActiveX Automation

Examining a TCP Application in LabWindows/CVI

To examine a TCP client/server application written in LabWindows/CVI. If the


teaching facility has networked computers, you can try running the application
across the network.
The client program requests one of several waveforms to be generated by the
server. The server either acquires the data from the GPIB device simulator
or creates the data using the signal generation routines in the Advanced
Analysis Library. This allows you to try out the application without the
GPIB device simulator. After either acquiring or creating the data, the server
plots the data on the user interface and sends the waveform data back to the
client. Upon receiving the entire array of data, the client also plots the
waveform.

Part A: Running the Application


1. Open and create a debuggable executable for the respective projects.
Select BuildCreate Debuggable Executable.

For servers: Open TCPSER.PRJ located in the directory


C:\Exercises\CVI Basics II\Lesson 3\ TCPSER.PRJ.

For clients: Open TCPCLI.PRJ located in the directory


C:\Exercises\CVI Basics II\Lesson 3\TCPCLI.PRJ.

2. Run the server executable. Enter an unused port number and select a data
source. If the data source is GPIB, enter the GPIB address of the device
simulator (most likely 2).

Run the client executable. Click the Connect to Server button. Enter the
IP address and port number of the server in the respective fields. When
connected, the client shows the IP address and the port number in the
Connected to field. After the client connects to the server, the Request
Data button is enabled. Select a waveform type and then click the

National Instruments Corporation

3-75

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Advanced button. After the server gathers the data and sends it to the
client, the client automatically plots the waveform to the screen.
3. When you are done, quit the programs by clicking the Quit button.

Part B: Examining the Client

Open tcpcli.prj located in the directory C:\Exercises\CVI


Basics II\Lesson 3\tcpcli.prj. Open tcpcli.c and examine
the source code. Functions that this exercise describes are tagged.

The ConnectServer callback functions prompts you to enter the IP


address and port of the server you want to connect to, if you are not
already connected to the server. ConnectToTCPServer function uses
these values along with the TCP client callback function pointer. One of
the parameters returned is the conversation handle. This handle is used
in subsequent client reads and writes.

TCPClientCB callback function handles the TCP_DATAREADY and


TCP_DISCONNECT events.

Upon receiving a TCP_DATAREADY event, the client reads the


data array with ClientTCPRead. In this function, specify the
conversation handle, the name of the array to store the data in,
the amount to read, and a timeout. Once the data is received, it is
plotted to the user interface with PlotY.

Upon getting a TCP_DISCONNECT event, the client informs the user


that the server has terminated connection.

The RequestData callback executes when the user clicks the Request
Data button. This function then reads the Waveform Select ring control
and formats a command string using the Fmt function, which is similar
to the ANSI C sprintf function. This command string is passed to
ClientTCPWrite along with the conversation handle, the number of
bytes, and a timeout.

LabWindows/CVI Basics II Course Manual

3-76

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

The Quit function disconnects the client from the server with
DisconnectFromTCPServer and exits the user interface.

Close the Source window. Do not save any changes.

Part C: Examining the Server

Open tcpser.prj located in the directory C:\Exercises\CVI


Basics II\Lesson 3\tcpser.prj. Open tcpser.c.

Press <F2> to move to the main function. When the program starts, it
prompts the user to enter the port address for the server to use. Then the
program executes RegisterTCPServer and specifies this port address
and the server callback function. There is no need to give an IP address,
because RegisterTCPServer identifies the IP address from the
Windows environment.

The next tagged function is TCPServerCB, which handles all of the


TCP events.

Upon getting a TCP_CONNECT event, the server increments the


current amount of clients connected and displays that amount to the
user interface.

Upon getting a TCP_DISCONNECT event, the server decrements


the current amount of clients connected and displays that amount to
the user interface.

Upon getting a TCP_DATAREADY event, the server reads from


the client using ServerTCPRead. In this function, pass the
conversation handle for that client, a data buffer to hold the data,
the number of bytes to read, and a timeout. The server then parses
the data buffer to find out what type of waveform the client requests.
Depending on whether the data is simulated or acquired using the
GPIB device simulator, the server gets the data, plots it to the graph,
and then sends it to the client using ServerTCPWrite. The
parameters passed are identical to those passed in ServerTCPRead
except that now you are specifying the source data buffer rather than
a target.

The last tagged function is Quit. In this callback, the server executes
an UnregisterTCPServer to unregister itself and exit the user
interface.

Close the Source window. Do not save any changes.

End of Exercise 3-9

National Instruments Corporation

3-77

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Summary Lesson 3
ActiveX Automation and how to create ActiveX
clients in LabWindows/CVI
DataSocket technology, which provides a high-level
API to transfer data between different entities
Connecting to LabVIEW from LabWindows/CVI
using ActiveX
TCP and using TCP to control applications on the
network
Summary Lesson 3
In this lesson, you learned how LabWindows/CVI can interact with other applications using a
variety of methods.

ActiveX AutomationWith ActiveX Automation, you can use the methods and control the
properties of objects from other applications instead of recreating the functionality within
LabWindows/CVI.

DataSocketWith DataSocket, you can transfer live data from application to application(s)
regardless of the underlying data protocol.

TCPWith TCP, you can communicate between simultaneously running applications over a
network connection.

Each technology has a client-server architecture, and it is important that you understand the role
each one plays.
If you want to combine the power of graphical programming with C-based programming, you can
connect to LabVIEW through VI Server or convert LabWindows/CVI instrument drivers to
LabVIEW instrument drivers.

LabWindows/CVI Basics II Course Manual

3-78

ni.com

Lesson 3

Interapplication Communication and ActiveX Automation

Notes

National Instruments Corporation

3-79

LabWindows/CVI Basics II Course Manual

Lesson 3

Interapplication Communication and ActiveX Automation

Notes

LabWindows/CVI Basics II Course Manual

3-80

ni.com

Code Modularity and Compatibility

Lesson 4: Code Modularity and Compatibility


A. Using dynamic link libraries (DLLs)
B. Porting code between development environments

Introduction
When you develop large applications, consider designing them in a modular fashion. This means
that the application is partitioned into distinct modules. Each module possesses a logical grouping
of functions or achieves a specific functionality.
This modularity serves several purposes:

Helps organize code development among a team of programmers

Simplifies future code modification

Aids in the reuse of code in other programs

Modules can be source files, object files, static libraries, and dynamic link libraries (DLLs). Each
of these modules has different advantages and disadvantages. In this lesson, you will learn how to
create and use DLLs. Later in this lesson, we will discuss issues regarding porting code between
development environments.

National Instruments Corporation

4-1

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Modules
What are modules?
Types of modules

Source files (*.c)


Object files (*.obj)
Static libraries (*.lib)
Dynamic link libraries (*.dll)

Modules
In C programming, the instructions to the computer reside in one or more files. The files that
actually contain code and are translated into machine instructions are called modules. Normally,
a program consists of more than one module. The following list describes the different kinds of
modules.

Source files.c files are text files that contain code in C grammar. The compiler compiles
this code into an object file and generates executable code out of the source file.

Object files.obj files, which are in binary format, are usually generated from source files
and are linked with other object and library files to generate the final program. The object files
contain tables with symbolic information about the functions and variables in the original
source code.

Static Library files.lib files, which are in binary format, are usually a collection of object
files. These files are used to organize a set of related functions into one module, which allows
for easy access from various other source and object modules. For example, the analysis
functions in LabWindows/CVI are organized in the analysis.lib module. These files are
linked in by the LabWindows/CVI linker to create the executable program.

Dynamic Link Libraries (DLLs).dll files are binary files, but they differ from object and
static library files in that they are fully resolved, meaning that the functions inside a DLL do
not depend on any other module. The code inside a DLL is linked in only when the program is
executed, not when the program is created.

How does the compiler know, when creating the program, which functions to call in the DLL and
where the functions are located inside the DLL? This information is provided by a file known as
the import library for that DLL. The import library, .lib, is a static library file and contains code

LabWindows/CVI Basics II Course Manual

4-2

ni.com

Lesson 4

Code Modularity and Compatibility

to reliably link to the functions in the DLL at run time. As the name suggests, import libraries
contain code to import code from DLLs.
Header (.h) files are not modules. Header files do not contain code that can be translated into
machine instructions. Header files provide prototyping information for functions defined in
modules. The information inside a header file is always reproduced in source modules by the
#include directive.

National Instruments Corporation

4-3

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Dynamic Link Library (DLL)


Dynamic linking versus static linking
Advantages of dynamic linking

Flexibility in changing code (modularity)


Size of executable
Multiple applications accessing one DLL
Portability

Dynamic Link Library (DLL)


In high-level programming languages, an application source code must be compiled and linked to
various libraries to create an executable file. These libraries contain object files of precompiled
functions. When these library functions are linked to an application, they become a permanent part
of the application executable file. All calls to the libraries are resolved at link time, which is
referred to as static linking. Most Windows applications take advantage of dynamic linking, which
provides a mechanism to link applications to libraries at run time. These libraries reside in their
own binary files and are not copied into the application executable files as with static linking. These
libraries are called dynamic link libraries to emphasize that they are linked to an application when
the application is executed, rather than when the executable is created. When an application uses a
DLL, the operating system loads the DLL into memory, resolves references to functions in the DLL
so that the functions can be called by the application, and unloads the DLL when it is no longer
required. This process uses information present in the import library for that DLL.
When the program requires changes in DLL code, the executable does not necessarily need to be
rebuilt. For example, if you make a DLL as an instrument driver, you can ship a new DLL when
you add new features to the instrument driver. You are not required to rebuild the entire application.
Another advantage of dynamic linking is that the programs executable size becomes smaller due
to a non-linked DLL file. Your executable requires less memory from Windows and loads functions
in the DLL only when necessary. The DLL has internal code that allows its functions to be accessed
by simultaneously executing programs, which also saves memory. If several applications access the
same DLL functions, only one copy of the DLL is necessary on the system. If those applications
were to statically link the functions, each executable would have its own copy of the functions,
which wastes memory.

LabWindows/CVI Basics II Course Manual

4-4

ni.com

Lesson 4

Code Modularity and Compatibility

The disadvantage of using DLLs is that the complexity of application development increases. Your
application is no longer simply packaged into a single executable file. The executable requires the
DLLs it calls to be present on the target system. Because the code inside DLLs does not depend on
any other modules, you can port code from one environment to another in the form of DLLs, rather
than in the form of object and library files.

National Instruments Corporation

4-5

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Creating DLLs
Relationship between DLL, import library, and header files
Target Settings dialog box
DLL Files

DLL Source Code

.dll

Function
Definitions

.lib (import library)

DLL Header
Prototypes of
Exported Functions

Creating DLLs
Creating a DLL is not any more difficult than creating a static C library or an object module.
Although DLLs are linked at run time whereas static libraries are linked when the build occurs,
their source code can be identical. For example, you can take an existing source file for a static
library, change the BuildTarget Type setting in LabWindows/CVI to Dynamic Link Library,
and build the DLL. One difference in source code is that a DLL can contain a DllMain function.
The DllMain function is called whenever an application loads or unloads the DLL. This action
provides you with a mechanism to perform initializations when the DLL is first loaded, which is
similar to a constructor in C++, and to free system resources/cleanup when the DLL is unloaded,
which is similar to a destructor in C++. If you do not explicitly define a DllMain,
LabWindows/CVI creates a default one that does nothing.
The functions inside a DLL can either be internal to the DLL or callable from other modules. The
functions that are callable from other modules are said to be exported from the DLL. To create the
DLL properly, the compiler must know which functions to export. In LabWindows/CVI, create a
header file containing the prototypes of the functions you want to export from the DLL. Add this
header file to the project. When a program uses a DLL, it can access only the functions or variables
that the DLL exports. The DLL can export only globally declared functions and variables. The
DLL cannot export functions and variables you declare as static. In the Target Settings dialog box,
you select from a list of all the include files in the project. The include file method does not work
with other compilers. However, it is similar to the .def method that some other compilers use.
LabWindows/CVI creates the DLL and the appropriate import library for that DLL, and this import
library must be linked to any program that calls the functions exported from the DLL.

LabWindows/CVI Basics II Course Manual

4-6

ni.com

Lesson 4

Code Modularity and Compatibility

Calling Conventions
What are calling conventions for functions?
How do you specify a calling convention?
Terms to know
__stdcall
__cdecl
DLLSTDCALL

Calling Conventions
When functions are called from your program, the arguments of the function are placed on the stack
in a particular order. In addition, either the calling program or the function itself is responsible for
cleaning up the stack. To set up this order and cleaning role, use a calling convention within your
function declaration. If you intend for only C or C++ programs to use your DLL, you can use the
__cdecl calling convention for the functions you want to export. If you want your DLL to be
callable from programs written in Microsoft Visual Basic or Pascal, you must declare the functions
you want to export with the __stdcall calling convention. You must explicitly define functions
with the __stdcall keyword (notice the double underscore __ in front of the words) whether or
not you choose to make __stdcall the default calling convention for your project. You must use
the __stdcall keyword in the declarations in the include file you distribute with the DLL. Other
platforms, such as Windows 3.1, do not recognize the __stdcall keyword. If you work with
source code that you might use on other platforms, use a macro in place of __stdcall. The macro
translates to the appropriate calling convention. The cvidef.h include file defines the
DLLSTDCALL macro for this purpose. The following example code uses the DLLSTDCALL macro.
int DLLSTDCALL MyIntFunc (void);
char * DLLSTDCALL MyStringFunc (void);

NI recommends that you use the DLLSTDCALL macro instead of __stdcall.

National Instruments Corporation

4-7

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Using DLLs
Link in the import library
Call functions as prototyped in the header
Put the DLL in the Windows system folder or in the current
project folder
Program

module1
Import Library
module2
DLL

Header

Using DLLs
When you use the functions of a DLL in one of your programs, you must add the import library to
your project so that it gets linked into the program. You also must call the functions in the DLL
according to the prototypes in the DLL header file, which you can accomplish by #including the
header file into the modules from which the functions are called. Place the DLL in the Windows
system folder or the folder in which the project exists, so that the DLL can be located and loaded
at run time.

LabWindows/CVI Basics II Course Manual

4-8

ni.com

Lesson 4

Code Modularity and Compatibility

Exercise 4-1

OBJECTIVE

Time to complete: 15 min.

To create a DLL in LabWindows/CVI

National Instruments Corporation

4-9

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Exercise 4-1
Objective:

Creating a DLL in LabWindows/CVI

To create a DLL in LabWindows/CVI.


In this exercise, you will build a DLL that can be accessed by other
programming languages.
1. Create a new project.
2. Select BuildTarget TypeDynamic Link Library.

3. Create a new source file. Enter the following code or copy and paste the
code from firstdll.c in the C:\Solutions\CVI Basics II\
Exercise 4-1 directory.

LabWindows/CVI Basics II Course Manual

4-10

ni.com

Lesson 4

Code Modularity and Compatibility

Notice that DllMain has the __stdcall keyword before it.


This keyword defines the calling convention for the function. Microsoft
Windows contains two calling conventionsthe C calling convention,
denoted by __cdecl, and the standard calling convention, formerly the
Pascal calling convention, denoted by __stdcall.
4. Save this file in the C:\Exercises\CVI Basics II\Lesson 4
directory as firstdll.c and add it to the project by selecting File
Add firstdll.c to Project.
5. Create a new header file and enter the following code:
void fnDLLTest(void);

Save this file as firstdll.h and add it to the project.


6. Save the project as firstdll.prj.
7. Select BuildTarget Settings. The Target Settings dialog box appears.

National Instruments Corporation

4-11

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

8. Click the Import Library Choices button. In the DLL Import Library
Choices dialog box, select Generate import libraries for both
compilers and click OK.
When you select this option, LabWindows/CVI creates import libraries
for both supported compilers in subdirectories under the projects root.

9. Click the Change button in the Exports section. In the DLL


Export Options dialog box, check firstdll.h, then click OK.
LabWindows/CVI uses this header file to determine what functions to
export. The only function prototype in the header file is for fnDLLTest,
so it is the only function exported. Click OK to return to the Workspace
window.
10. Select BuildConfigurationRelease.
11. Select BuildCreate Release Dynamic Link Library. Click OK if
prompted to set debugging to none to create the DLL.

LabWindows/CVI Basics II Course Manual

4-12

ni.com

Lesson 4

Code Modularity and Compatibility

12. After the build completes, the following message appears.

By default, the DLL and import libraries created have the same base
name as the project. In this case, firstdll.dll is created along with
three copies of firstdll.lib, the import library.
LabWindows/CVI always creates one import library in the same
directory as the DLL. That import library is created with the current
compatibility mode, Visual C++. Import libraries for both supported
compilers also are created and stored in their respective subdirectories
(msvc and borland). If you want to distribute this DLL and you know
which compiler your DLL will be used with, then you need to ship the
DLL, the header file, and the import library for that particular compiler.
13. Click OK in the LabWindows/CVI message, save any changes, and
close all open windows except the Workspace window.

End of Exercise 4-1

National Instruments Corporation

4-13

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Exercise 4-2

OBJECTIVE

Time to complete: 10 min.

To use the DLL created in the previous exercise

LabWindows/CVI Basics II Course Manual

4-14

ni.com

Lesson 4

Exercise 4-2
Objective:

Code Modularity and Compatibility

Using a DLL Created in LabWindows/CVI

To use the DLL created in the previous exercise.


1. Create a new project. Save the project as testdll.prj in the directory
C:\Exercises\CVI Basics II\Lesson 4\testdll.prj.
2. Create a new source file. Enter the following code in the Source window:
#include "firstdll.h"
main()
{
fnDLLTest();
}

3. Save the file as testdll.c and add the file to the project.
4. Add the import library to the project so that the function can be resolved.
In the Workspace window, select EditAdd Files to ProjectLibrary
(*.lib). In the Add Files to Project dialog box, select firstdll.lib.
Click Add and then click OK.
5. Run the project. Four message pop-ups appear.

One for loading the DLL

One for the call to fnDLLTest

One for the internal call from fnDLLTest to fnInternal

One for unloading the DLL

6. Return to the Source window and add the following bolded lines to the
code:
#include "firstdll.h"
void fnInternal(void);
main()
{
fnInternal();
fnDLLTest();
}

7. Recall that fnInternal was not exported when you created the DLL.
Therefore, when you try to run the project, you get an "Undefined
symbol" error when the project is linked.
8. Close testdll.c. Do not save any changes.

End of Exercise 4-2

National Instruments Corporation

4-15

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Debugging DLL Code


BuildConfigurationDebug
There are two ways to debug DLLs
Run a program in LabWindows/CVI
Run an external process

Debugging DLL Code


Typically, you should debug the code for your DLL before building and using your DLL.
Sometimes you might debug the code in your DLL to solve run-time problems. LabWindows/CVI
provides a method to debug when you build and use your DLL in the LabWindows/CVI
environment. If you select BuildConfigurationDebug and select BuildTarget Type
Dynamic Link Library, the Create Debuggable Dynamic Link Library command appears in
the Build menu. When you select Create Debuggable Dynamic Link Library, LabWindows/CVI
includes debug code in your DLL and generates extra files that contain code and source position
information necessary for debugging. To debug a DLL in LabWindows/CVI, the source files for
the DLL must be available. You cannot debug DLLs you create in LabWindows/CVI in other
development environments.
You can debug a DLL two ways:

Run a LabWindows/CVI project that calls the DLL. In this case, the DLL project is not open.

Open the DLL project and run an external process that uses the DLL.

To debug a DLL that another LabWindows/CVI project uses, you must run the project with the
debugging level set to a value other than none. When LabWindows/CVI loads the DLL, it loads the
corresponding debug information from the auxiliary debug files. LabWindows/CVI honors the
breakpoints you set in DLL source files. LabWindows/CVI saves in the project any breakpoints you
set in source files, regardless of whether the source file is in the project. You also can set watch
expressions for a debuggable DLL. For each watch expression, you must choose whether the watch
expression applies to a project or a DLL. If the watch expression applies to a DLL, you must enter
the name of the DLL. LabWindows/CVI stores this information in the project.

LabWindows/CVI Basics II Course Manual

4-16

ni.com

Lesson 4

Code Modularity and Compatibility

To debug a DLL that an external process uses, load the DLL project into LabWindows/CVI. Make
sure you set the debugging level to a value other than none. Select RunSpecify External Process.
A dialog box appears in which you enter the pathname and command line arguments to an external
program. LabWindows/CVI stores this information in the project. The RunRun Project
command changes to Debug xxx.exe, where xxx.exe is the filename of the external program.
When you execute the Debug xxx.exe command, LabWindows/CVI starts the external process and
attaches to it for debugging. If you have set any breakpoints in the source files for the DLL,
LabWindows/CVI honors them. If the external process loads other debuggable DLLs, you can
debug them even though the project for a different DLL is open.

National Instruments Corporation

4-17

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Exercise 4-3

OBJECTIVE

Time to complete: 20 min.

To learn the DLL debugging features

LabWindows/CVI Basics II Course Manual

4-18

ni.com

Lesson 4

Exercise 4-3
Objective:

Code Modularity and Compatibility

Examining DLL Debugging Features

To learn about the DLL debugging features.


1. Open firstdll.prj located in the directory C:\Exercises\CVI
Basics II\Lesson 4\firstdll.prj.
2. Select BuildConfigurationDebug to enable DLL debugging.
3. Rebuild the DLL. Select BuildCreate Debuggable Dynamic Link
Library, overwriting the existing DLL and import library files.
4. After the build completes, the following window appears.

5. Click OK in the LabWindows/CVI message.


6. Open the testdll.prj project.
7. Open firstdll.c, the source file for the DLL created in step 3.
8. Place your cursor on line 12 (MessagePopup ("In DLLMain",
"I've been unloaded");) and insert a breakpoint by selecting
RunToggle Breakpoint.
9. Run the testdll.prj project. LabWindows/CVI breaks at the
appropriate statement in the DLL source file. You also can add watch
expressions for variables in the DLL through the Watch window, as
shown in the following figure.

National Instruments Corporation

4-19

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Try adding watch expressions for other variables and see the different
settings applicable for variables defined in DLLs.
10. After testing the different DLL debugging features, close all files.

End of Exercise 4-3

LabWindows/CVI Basics II Course Manual

4-20

ni.com

Lesson 4

Code Modularity and Compatibility

DLL Recommendations
Use DLLSTDCALL
Use the include file method
Avoid exporting variables. Use functions to set/get the
values of variables
Debug your DLL code as much as possible before creating
the DLL. Use DLL debugging to debug run-time problems.

DLL Recommendations
To simplify DLL creation, use the following recommendations:

Use the DLLSTDCALL macro in the declaration and definition of all functions you want to
export. Do not export functions with a variable number of arguments.

Identify the symbols you want to export using the include file method. Do not use export
qualifiers. If you use an external compiler, use the .def file method.

Do not export variables from the DLL. For each variable you want to export, create functions
to get and set the variable value or create a function that returns a pointer to the variable. Do
not use import qualifiers in the include file.

These recommendations bring the following benefits:

You can distribute with your DLL the same include file that you include in the source files you
use to make the DLL. This distribution is especially useful when you create DLLs from
instrument drivers.

You can use the same source code to create the DLL in LabWindows/CVI and both of the
compatible external compilers.

You can use your DLL in Microsoft Visual Basic or other non-C environments.

National Instruments Corporation

4-21

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Compatibility With External Compilers


What is meant by compatibility?
Compatibility issues with source, object code, static
library, and so on
Compatible compilers
Microsoft Visual C/C++
Borland C/C++

Compatibility with External Compilers


Compatibility is the ability to use modules created in one compiler with another compiler. Source
code is compatible as long as it is ANSI C, but the situation is complicated for modules in binary
format, such as object and library files. Compatibility does not apply to executables because they
contain machine instructions.
LabWindows/CVI is compatible at the object code level with two compatible external compilers,
Microsoft Visual C/C++ and Borland C/C++. Because these compilers are not compatible with
each other at the object code level, LabWindows/CVI is compatible with only one external
compiler at a time.
If you want to change the compatible compiler, select OptionsBuild Options and choose
Visual C/C++ or Borland C/C++ from the Compatibility with control in the Build Options
dialog box. You must restart LabWindows/CVI after changing the compiler compatibility.
If you create an object file, library file, or DLL import library in LabWindows/CVI in a certain
compatibility format, you can use the file only in the current compatible compiler or in
LabWindows/CVI if LabWindows/CVI has the same compatibility mode.

LabWindows/CVI Basics II Course Manual

4-22

ni.com

Lesson 4

Code Modularity and Compatibility

Using LabWindows/CVI Libraries in External


Compilers
Require the LabWindows/CVI Run-Time Engine
Compatibility files are in C:\Program Files\National
Instruments\CVI\extlib

Always link in cvisupp.lib and cvirt.lib

Using LabWindows/CVI Libraries in External Compilers


The LabWindows/CVI Run-Time Engine contains all the built-in library, memory, and program
execution code present in the LabWindows/CVI development environment, without program
development tools such as the source editor, compiler, debugger, and User Interface Editor. The
LabWindows/CVI Run-Time Engine consists of multiple files, including DLLs such as
cvirt.dll, cvirte.dll, and cviauto.dll. Executable files and DLLs you create in
LabWindows/CVI use the LabWindows/CVI Run-Time Engine.
The C:\Program Files\National Instruments\CVI\extlib directory contains libraries
for your current compatible compiler. Never use the .lib files in the C:\Program Files\
National Instruments\CVI\bin directory in an external compiler. You always must include
the following two libraries in your external compiler project.

cvisupp.libstartup library

cvirt.liblibrary related to User Interface, Formatting and I/O, RS-232, DDE Support,

TCP Support, and Utility Library functions


If you use an external compiler that requires a WinMain entry point, include cviwmain.lib.
Using this .lib file, you can define only main in your program.
To initialize the LabWindows/CVI Run-Time Engine, you must call InitCVIRTE before calling
any other LabWindows/CVI functions. Normally, you call this function in your modules
entry-point, like main, WinMain, or DllMain. When you finish with the LabWindows/CVI
Run-Time Engine, call CloseCVIRTE.

National Instruments Corporation

4-23

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

You can add the analysis.lib static library file, which contains the Analysis (or Advanced
Analysis) Library, from C:\Program Files\National Instruments\CVI\extlib
directory to your external compiler project.

LabWindows/CVI Basics II Course Manual

4-24

ni.com

Lesson 4

Code Modularity and Compatibility

Using LabWindows/CVI Libraries in External


Compilers (cont.)
Link in other libraries as necessary
Include files and Standard I/O window
Call InitCVIRTE and CloseCVIRTE

Using LabWindows/CVI Libraries in External Compilers (cont.)


You can add the following DLL import library files from C:\Program Files\National
Instruments\CVI\extlib to your external compiler project.

gpib.libGPIB/GPIB 488.2 Library

dataacq.libTraditional NI-DAQ Library

nidaqmx.libNI-DAQmx Library

visa.libVISA Library

nivxi.libVXI Library

ivi.libIVI Library

cviauto.libActiveX Library

The cvirt.lib library file contains symbols for all the LabWindows/CVI libraries, except the
ANSI C Library. When you create an executable or DLL in an external compiler, you use the
compilers own ANSI C standard library. Because of this, you must use the external compilers
include files for the ANSI C library when compiling source files. Although the include files for the
other LabWindows/CVI libraries are in the C:\Program Files\National Instruments\
CVI\include directory, the LabWindows/CVI ANSI C include files are in the C:\Program
Files\National Instruments\CVI\include\ansi directory. Thus, you can specify
C:\Program Files\National Instruments\CVI\include as an include path in your
external compiler while, at the same time, using the external compilers version of the ANSI C
include files.

National Instruments Corporation

4-25

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

One effect of using the external compilers ANSI C standard library is that the printf and scanf
functions do not use the LabWindows/CVI Standard Input/Output window. To use printf and
scanf, you must create a console application. To continue using the LabWindows/CVI Standard
Input/Output window, call the FmtOut and ScanIn functions in the Formatting and I/O Library.

LabWindows/CVI Basics II Course Manual

4-26

ni.com

Lesson 4

Code Modularity and Compatibility

Other Issues with External Compilers


Compiler options
Which header files to use?
Non-ANSI extensions

Other Issues with External Compilers


Choose external compiler options carefully. LabWindows/CVI works with the default options for
each compiler. You must not use certain options to override the defaults. Refer to the Programmer
Reference section of the LabWindows/CVI Help for compiler options to avoid.
You must set up your include paths differently depending on the environment in which you compile
and link. A discussion of each case follows:
Compiling in LabWindows/CVI for Linking in LabWindows/CVI
Use the LabWindows/CVI SDK and ANSI C include files. You do not need to set up any special
include paths; LabWindows/CVI finds the correct include files automatically.
Compiling in LabWindows/CVI for Linking in an External Compiler
Use the LabWindows/CVI SDK include files and the ANSI C include files from the external
compiler. Use the Include Paths dialog box to add the following paths as explicit include paths at
the beginning of the project-specific list. Open the Include Paths dialog box by selecting Options
Environment and clicking the Include Paths button.

CVI\include

CVI\sdk\include

Directory that contains the external compilers ANSI C include paths

Compiling in an External Compiler for Linking in an External Compiler


Use the SDK and ANSI C include files from the external compiler. This action happens
automatically. Specify C:\Program Files\National Instruments\CVI\include as an
include path in the external compiler for the LabWindows/CVI library include files.

National Instruments Corporation

4-27

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Other Issues with External Compilers (cont.)


C++ name decoration, name mangling
Compatibility issues with DLLs

Other Issues with External Compilers (cont.)


Compiling in an External Compiler for Linking in LabWindows/CVI
Use the LabWindows/CVI SDK and ANSI C include files. Specify the following directories as
include paths in the external compiler.

CVI\include

CVI\include\ansi

CVI\sdk\include

LabWindows/CVI does not work with all non-ANSI extensions each external compiler provides.
Also, in cases where ANSI does not specify the exact implementation, LabWindows/CVI does not
always agree with external compilers. Most of these differences are unclear and rarely encountered.
Refer to the Programmer Reference section in the LabWindows/CVI Help for details.
C++ Name Decoration
Use extern "C" {/* definitions in source code */ } to prevent C++ compilers/linkers
from decorating symbol names. Doing so allows for portability of code that might be linked in a
C or C++ compiler/linker. The following code is an example:
#ifdef __cplusplus
extern "C" {
#endif
/* Definitions in the Source Code*/
#ifdef __cplusplus

LabWindows/CVI Basics II Course Manual

4-28

ni.com

Lesson 4

Code Modularity and Compatibility

}
#endif

Compatibility Issues with DLLs


Only the DLL import library must be created for the current compatible compiler. Some cases exist,
however, in which you cannot call a DLL that you created using one compiler from an executable
or DLL that you created using another compiler. If you want to create DLLs that you can use in
different compilers, design the Application Programming Interface (API) for your DLL to avoid
such problems. Refer to the Programmer Reference section in the LabWindows/CVI Help for
information about possible problems and solutions to these problems.

National Instruments Corporation

4-29

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Using the User Interface Library with External


Compilers
How are callback functions handled in external compilers?
Object file with table containing callback function
symbols required for external compilers
Linking to callback functions not exported from a DLL

Using the User Interface Library with External Compilers


When you link your user interface programs, LabWindows/CVI keeps a table of the non-static
functions present in your project. When your program calls LoadPanel or LoadMenuBar, the
User Interface Library uses this table to find the callback functions associated with the objects you
loaded from the user interface resource (.uir) file. This is true whether you run your program in
the LabWindows/CVI development environment or as an executable. When you write your
callback functions in an external compiler, the external compiler does not make such a table
available to the User Interface Library. To resolve callback references, you must use
LabWindows/CVI to generate an object file that contains the necessary table. Create this table
using the following procedure:
1. Create a LabWindows/CVI project that contains the .uir files your program uses, if you do
not already have one.
2. Select BuildExternal Compiler Support. The External Compiler Support dialog box
appears.
3. In the UIR Callbacks box, enter the pathname of the object file you want to generate. When
you click the Create button, LabWindows/CVI generates an object file with a table that
contains the names of all the callback functions referenced in the .uir files of the project.
When you modify and save any of these .uir files, LabWindows/CVI regenerates the object
file to reflect the changes.
4. Include this object file in the external compiler project you use to create the executable.
5. Call InitCVIRTE at the beginning of your main or WinMain function.
When you load a panel or menu bar from a DLL, you can link to non-static callback functions the
DLL contains but does not export. To link to callbacks, call LoadPanelEx and LoadMenuBarEx.

LabWindows/CVI Basics II Course Manual

4-30

ni.com

Lesson 4

Code Modularity and Compatibility

When you pass the DLL module handle to LoadPanelEx and LoadMenuBarEx, the User
Interface Library searches the table of callback functions the DLL contains before searching the
table that the executable contains.
In summary, if you want to use LabWindows/CVI user interface features in an external compiler,
you must create the user interface resource in LabWindows/CVI. You can then write your callback
functions within a LabWindows/CVI DLL or you can write them inside an external compiler. If
you take the latter approach, you must include the UIR Callbacks object file.

National Instruments Corporation

4-31

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Exercise 4-4 (Optional)

OBJECTIVE

Time to complete: 10 min.

To create an object file containing UIR callback support for


use in an external compiler

LabWindows/CVI Basics II Course Manual

4-32

ni.com

Lesson 4

Exercise 4-4
Objective:

Code Modularity and Compatibility

Creating an Object File for Use in an External


Compiler (Optional)

To create an object file containing UIR callback support for use in an external
compiler.

Note This exercise requires that you use the Borland external compiler. To import a
LabWindows/CVI project into Microsoft Visual C++, choose the NI Measurement
Studio AppWizard when you create a new project in Measurement Studio. This utility
provides the option to automatically convert LabWindows/CVI programs, applications,
and libraries into Microsoft Visual C++ applications.

1. Create a new project. Save the project as chart.prj in the directory


C:\Exercises\CVI Basics II\Lesson 4\chart.prj.
2. Open chart.uir located in the directory C:\Exercises\
CVI Basics II\Lesson 4\chart.uir. Add this UIR to the
project. The UIR contains a chart, a timer control, and command button.
The timer control has a callback named PlotToChart and an interval
of 100 ms. The command button has a callback function named
QuitProgram.
3. Create a program shell using CodeBuilder. Select CodeGenerate
All Code.
4. In the Generate All Code dialog box, enable Generate WinMain()
instead of main() and select QuitProgram in the Select
QuitUserInterface Callbacks box. Also, make sure that you select
Add to Current Project in the Target Files section and click the OK
button.

National Instruments Corporation

4-33

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

5. Add the following line to the PlotToChart callback function in the


case statement for EVENT_TIMER_TICK.
PlotStripChartPoint (panelHandle, PANEL_STRIPCHART,
rand()/327.67);

6. Use LabWindows/CVI to test the program before going to the external


compiler to create the executable. Run the project, add any necessary
header files and view the strip chart.

LabWindows/CVI Basics II Course Manual

4-34

ni.com

Lesson 4

Code Modularity and Compatibility

7. If the program runs as expected, click Quit to return to the Workspace


window.
8. Now that you have verified that the program works, you can take this
source file to an external compiler to run. Recall that you must create
a callback object file for callbacks to work in the external environment.
In the Workspace window, select BuildExternal Compiler Support.
In the External Compiler Support dialog box, select Object File for UIR
Callbacks, browse to chartcb.obj in the name field, and click the
Create button.
9. Click the OK button.

10. After creating the file, close all windows except the Workspace window.

End of Exercise 4-4

National Instruments Corporation

4-35

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Exercise 4-5 (Optional)

OBJECTIVE

Time to complete: 15 min.

To create a DLL in LabWindows/CVI that contains callback


functions for use in an external compiler

LabWindows/CVI Basics II Course Manual

4-36

ni.com

Lesson 4

Exercise 4-5
Objective:

Code Modularity and Compatibility

Creating a DLL for Use in an External Compiler


(Optional)

To create a DLL in LabWindows/CVI that contains callback functions for use in an


external compiler.
1. Create a new project and select BuildTarget TypeDynamic Link
Library. This step is necessary for CodeBuilder to generate the
appropriate code. Save the project as chart2.prj in the directory
C:\Exercises\CVI Basics II\Lesson 4\chart2.prj.
2. Open C:\Exercises\CVI Basics II\Lesson 4\chart.uir.
Save the file as chart2.uir in the directory C:\Exercises\CVI
Basics II\Lesson 4\chart2.uir and add it to the project.
3. Select CodeGenerateAll Code.
4. In the Generate All Code dialog box, enable Generate WinMain()
instead of main() and select QuitProgram in the Select
QuitUserInterface Callbacks box. Also, make sure that you select
Add to Current Project in the Target Files section. Click OK.
5. The resulting Source window contains the callback functions for
PlotToChart and Shutdown and the DllMain function. In addition,
the InitUIForDLL function loads and displays the user interface panel.
Uncomment RunUserInterface line as shown in the following figure.

6. Add the following line to the PlotToChart callback function in the


case statement for EVENT_TIMER_TICK.
PlotStripChartPoint (panelHandle, PANEL_STRIPCHART,
rand()/327.67);

7. Select BuildCompile chart2.c. Add any necessary header files when


prompted. Close the Source window, saving any changes.

National Instruments Corporation

4-37

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

8. The InitUIForDLL function is called from the external compiler to


enable the GUI. Therefore, you must export this function for the external
compiler. To do so, create a new header (.h) file.
9. In the header file, enter
int InitUIForDLL (void);

Save this file as exportme.h. Add it to the project and close the
window.
10. In the Workspace window, select BuildTarget Settings.
11. Click the Import Library Choices button. In the DLL Import Library
Choices dialog box, select Generate import libraries for both
compilers and click OK. Selecting this option creates import libraries
for both supported compilers in subdirectories under the projects root.
12. Click the Change button in the Exports section. In the DLL Export
Options dialog box, check exportme.h, then click OK.
LabWindows/CVI uses this header file to determine what functions
to export.
13. Click OK to exit the Target Settings dialog box.
14. Select BuildConfigurationRelease.
15. To create the DLL, select BuildCreate Release Dynamic Link Library.

Using the DLL in LabWindows/CVI


16. Now that the DLL is created, you can try calling it from
LabWindows/CVI before trying it in your external compiler.
Create a new project and save it as testdll2.prj in the directory
C:\Exercises\CVI Basics II\Lesson 4\testdll2.prj.
17. Add the import library for the DLL to the project by selecting EditAdd
Files to ProjectLibrary (*.lib). In the Add Files to Project dialog box,
select chart2.lib. Click Add and then click OK.
18. Create a new source file and enter the following code.
#include "exportme.h"
main()
{
InitUIForDLL();
}

19. Save the source file as testdll2.c in the directory C:\Exercises\


CVI Basics II\Lesson 4\testdll2.c and add this file to the
project.
20. Run the project. The program should run as it did in Exercise 4-4.
21. Click the Quit button to exit.

End of Exercise 4-5


LabWindows/CVI Basics II Course Manual

4-38

ni.com

Lesson 4

Code Modularity and Compatibility

Summary Lesson 4
Use DLLs to add modularity to your programming
design
You can create and use DLLs from within
LabWindows/CVI
DLL debugging is available for DLLs created in
LabWindows/CVI
Understand the issues underlying the porting of code
between compilers

Summary Lesson 4
In this lesson, you learned about DLLs and the issues regarding the porting of code between
compilers.
Because a DLL is compiled code, follow the recommendations stated in the lesson when creating
a DLL. When troubleshooting programs, you can usually trace the source of the problem to a DLL.
For example, if you use a particular calling convention in your project and your DLL has a different
calling convention, the program might not function.
If you have only the header file for the DLL and not the import library, you can
generate the import library from the header file. Select OptionsGenerate DLL Import
Library when you open the header file.
Note

When porting code between development environments, make sure that if you use
LabWindows/CVI functions, you include the necessary header files, libraries (static or import), and
the LabWindows/CVI Run-Time Engine. Refer to the Programmer Reference section of the
LabWindows/CVI Help for information about portability and compatibility.

National Instruments Corporation

4-39

LabWindows/CVI Basics II Course Manual

Lesson 4

Code Modularity and Compatibility

Notes

LabWindows/CVI Basics II Course Manual

4-40

ni.com

Additional Topics
Lesson 5: Additional Topics

A. Multithreaded programming
B. Integrating the Windows Platform SDK
C. Useful utility functions

Introduction
This lesson covers the following topics, which extend the core functionality of LabWindows/CVI.

Using multiple threads in the same program to improve performance on multiprocessor


machines

Using the Platform SDK to add power and flexibility to your LabWindows/CVI application

Using miscellaneous utility functions for memory access, error handling, and handling
executables

This lesson also covers several advanced programming topics that can be optionally covered for the
individual needs of LabWindows/CVI users.

National Instruments Corporation

5-1

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Multithreading Terms
Multitasking
Multiple executables running concurrently
Preemptive versus non-preemptive

Multithreading
Multiple threads in a single executable

Multiprocessor machines
Multiple processors (CPUs) in a machine

Multithreading Terms

MultitaskingMultiple executables run at the same time. For example, you can download a
file using FTP while you edit a document in a word processing program.

Cooperative MultitaskingPrograms must explicitly give control back to the system


periodically so that another program is given a chance to execute. Windows 3.1 and MacOS are
examples of cooperative multitasking systems. Windows 3.x relies on cooperative,
non-preemptive multitasking, which requires that each running application periodically yield
control to Windows, which then allows another application to run.

Preemptive MultitaskingSystem periodically suspends a program to give other programs a


chance to execute. The program does not need to explicitly give control to the system. Each
program is executed for a few milliseconds and then suspended while other programs execute.
Windows NT/9x and Solaris are examples of preemptive multitasking systems.

MultithreadingMultiple threads execute in the same program. Unlike multitasking, all of


the threads have access to the global data in the program. Multithreaded programs require
support from the operating system. Windows XP/2000/NT/9x, Linux and Solaris 2 provide
support for multithreading.

Multiprocessor MachinesMachines with multiple processors increase performance if you


have preemptive multitasking or multithreading. Separate programs or threads run on each
CPU.

LabWindows/CVI Basics II Course Manual

5-2

ni.com

Lesson 5

Additional Topics

Multithreaded Programs
T
I
M

Word
Processor
Process
UI

Printing

Thread 1

Thread 2

E
Program

Multithreaded Programs
The large box represents a single process. The smaller boxes represent a single thread of execution.
From the user perspective, the UI responds to user input while the program is printing. On
multiprocessor machines or fast machines, the user might not be able to see a degradation of UI
responsiveness while a print operation is running.

National Instruments Corporation

5-3

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Benefits of Multithreading
Keep time-critical tasks from being greatly affected by UI
Keep UI responsive while performing command in
background
Printing in background

Improve throughput and performance on multiprocessor


machines
Logical separation of independent program parts

Benefits of Multithreading
The reliability of your data acquisition or control can increase by executing the data acquisition or
control in one thread while the UI executes in another thread.
You can execute lengthy operations in a spawned thread so that the main application thread always
can respond to UI events.
You can implement algorithms so that different pieces of the algorithm execute in separate threads.
If an algorithm that is implemented in such a manner is executed on a machine with multiple
processors, the algorithm executes faster than a traditional, single-threaded implementation of the
algorithm. A classic example is a compiler implemented in such a way that the preprocessor runs
in one thread and the actual compile runs in another thread, which results in improved throughput.
A more efficient implementation is a program in which independent pieces of the program run in
separate threads. For example, a TCP server application that responds to multiple clients is easier
to write if each client is handled by a separate thread in the server application.

LabWindows/CVI Basics II Course Manual

5-4

ni.com

Lesson 5

Additional Topics

Multithreading in LabWindows/CVI
Thread Pool
Thread creation
Thread Safe Queue
Passing data safely between multiple threads
Thread Safe Variables
Protecting data used in multiple threads
Thread Lock
Critical section or mutex in C
Prevents multiple access of data
Thread Local Variables
Per thread values for variables
Note: All threading functions are in Utility Library

Multithreading in LabWindows/CVI
With thread pools, you can schedule functions for execution in separate threads. Thread pools
handle thread caching to minimize the overhead associated with creating and destroying threads.
Thread safe queues abstract passing data between threads. One thread can read from a queue at the
same time that another thread writes to the queue.
Thread safe variables effectively combine a critical section and an arbitrary data type. You can call
a single function to acquire the critical section, set the variable value, and release the critical
section.
Thread lock simplifies using a critical section or mutex by providing a consistent API and using
the appropriate mechanism when necessary. For example, a mutex is used if the lock needs to be
shared between processes or if threads need to process messages while waiting for the lock. A
critical section is used in other cases because it is more efficient.
Thread local variables provide per-thread instances of variables. The operating system places a
limitation on the number of thread local variables available to each process. The LabWindows/CVI
implementation consolidates the thread local variables, using only one process thread local variable
for all of the thread local variables in your program. You can find all of the multithreading functions
in the LabWindows/CVI Library Tree under Utility LibraryMultithreading.

National Instruments Corporation

5-5

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Thread Pools
Thread pools manage groups of threads
Programs have a default thread pool
Max threads = 2 + 2*NumberOfProcessors

You can create additional thread pools


Use scheduling functions to create threads in a thread pool
Thread functions must have the following prototype:
int CVICALLBACK FuncName (void
*functionData);

Thread Pools
Thread pools are the mechanism for creating and managing threads in LabWindows/CVI.
LabWindows/CVI applications have one default thread pool. For many cases, creating additional
thread pools is unnecessary, and you can use the default thread pool instead. The default thread pool
can hold a maximum of 2 + 2*(NumberOfProcessors) threads, which translates into a maximum
of 4 threads for single processor machines and 6 threads for dual processor machines. If you need
more threads than the one that fits in the default thread pool, you can create an additional thread
pool. You also might want to create additional thread pools to group threads that have logical
connections. For example, you can use one thread pool for all data acquisition threads.
Creating thread pools does not create any actual threads. Threads are created by scheduling
functions in the thread pool with the CmtScheduleThreadPoolFunction. Functions that are
scheduled in threads can be named by anything. However, they must have a specific function
prototype:
int CVICALLBACK FuncName (void *functionData);

LabWindows/CVI Basics II Course Manual

5-6

ni.com

Lesson 5

Thread Pool Example

Additional Topics

Application
Default Thread Pool

1. Run program
2. Schedule function
func1 in default
thread pool
3. Create second
thread pool
4. Schedule function
func2 in second thread
pool

main()
thread

func1()
thread

New Thread Pool


func2()
thread

Thread Pool Example


When a LabWindows/CVI application begins running, the main function begins in one thread in
the default thread pool.
No allocation is performed for the default thread pool until the first function is
scheduled in it.
Note

When a function is scheduled in the default thread pool, the default thread pool is initialized and
the function begins running in a separate thread. In this case you can use the CmtNewThreadPool
function to create a second thread pool. CmtNewThreadPool returns a handle to the new thread
pool that you can use to schedule functions. Another function, func2, can be scheduled in the
second thread pool and begins running in another thread. This second thread pool must be
discarded in the program when it is no longer needed or when the program exits. To discard the
second thread pool, use CmtDiscardThreadPool.

National Instruments Corporation

5-7

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Thread Pool Example (cont.)


static int CVICALLBACK func1(void *functionData);
static int CVICALLBACK func2(void *functionData);
int main (int argc, char *argv[])
{
int stat;
int func1ID, func2ID;
int poolHandle;

...

CmtScheduleThreadPoolFunction
(DEFAULT_THREAD_POOL_HANDLE, func1, NULL,
&func1ID);
CmtNewThreadPool (4, &poolHandle);
CmtScheduleThreadPoolFunction (poolHandle,
func2, NULL, &func2ID);

Thread Pool Example (cont.)


The figure above shows the source code for creating the thread configuration. The source code for
the scheduled functions, func1 and func2, is not shown, but the function prototypes are given
according to the required format for thread functions.
CmtScheduleThreadPoolFunction is used twice to create two threads. The first thread is
created in the default thread pool. The second thread is created in the second thread pool. The
CmtNewThreadPool function is used to create the second thread pool. Before exiting the
program, the second thread pool must be discarded with the CmtDiscardThreadPool function.

LabWindows/CVI Basics II Course Manual

5-8

ni.com

Lesson 5

Additional Topics

Exercise 5-1

OBJECTIVE

Time to complete: 20 min.

To complete a simple multithreaded program in


LabWindows/CVI

National Instruments Corporation

5-9

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Exercise 5-1
Objective:

Multithreading in LabWindows/CVI

To complete a simple multithreaded program in LabWindows/CVI.


1. Open the threadpool.prj located in the directory C:\Exercises\
CVI Basics II\Lesson 5\threadpool.prj. This project is
partially completed. The user interface, shown in the following figure, is
composed of a panel with two command buttons, Create Thread and
Quit.

2. Open threadpool.c. The source code consists of four functions:


the main function, callbacks for the Create Thread and Quit buttons
(NewThread and Quit) and the thread function called
MyThreadFunction.
3. You must instantiate a thread pool before beginning to schedule threads.
Navigate to the /* Create thread pool here */ comment in the
main function. Insert the CmtNewThreadPool function under the
comment. From the Library Tree, select Utility Library
MultithreadingThread PoolAdvanced Functions
CmtNewThreadPool function and complete the function panel as
shown in the following table.
Maximum Number of Threads
Pool Handle

MAXTHREADS
&poolHandle

After you complete the function panel, select CodeInsert Function Call to
insert the function call into your source code.
Note

LabWindows/CVI Basics II Course Manual

5-10

ni.com

Lesson 5

Additional Topics

Note The default thread pool is not used because more threads are needed than are
available in the default thread pool.

4. The NewThread callback function is called when you click the Create
Thread button. This function checks to see if the maximum number of
threads (MAXTHREADS) has been reached. The NewThread function
instantiates a new control and places the control on the panel.
MyThreadFunction, which has already been written, updates the
control. You need to write code to create and schedule a thread that runs
the MyThreadFunction function. Navigate to the /* Schedule new
thread function here */ comment in the NewThread function
and insert a function call to the CmtScheduleThreadPoolFunction
below the comment to create a new thread. From the Library Tree, select
Utility LibraryMultithreadingThread PoolCall Scheduling
FunctionsCmtScheduleThreadPoolFunction and complete the
function panel as shown in the following table.
Pool Handle
Thread Function
Thread Function Data
Thread Function ID

poolHandle
MyThreadFunction
(void *)ctrlID
NULL

5. Add the following line to increment the numThreads variable below the
CmtScheduleThreadPoolFunction. This keeps track of how many
threads have been allocated.
numThreads++;

6. Navigate to the Quit callback function. This function shuts down all of
the threads and causes the program to stop executing. Enter exiting =
1; below the /* Discard thread pool here and set exiting
flag */ comment to stop the threads. After setting the exiting flag,
select Utility LibraryMultithreadingThread PoolAdvanced
FunctionsCmtDiscardThreadPool from the Library Tree and pass
poolHandle as the Pool Handle parameter. Insert the
CmtDiscardThreadPool function into the Source window.
7. Examine the thread function, MyThreadFunction. Notice how the
function uses the exiting flag to exit the function.
8. Build and run the project. Verify that the Create Thread button works
properly. As more threads are added, notice that they continue to run.
Also notice how the speed of each thread decreases as more threads
are created.

End of Exercise 5-1

National Instruments Corporation

5-11

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Thread Safe Queues

Safely pass arrays between threads


Data queue store data being passed between threads
Queue can be configured to resize when full
Queue can be event-based to trigger other threads when
queue is at a certain level
Good for multithreaded data acquisition
Use pointers or buffers to access data in queue

Thread Safe Queues


When you use multiple threads in a program, make sure that you consider data protection. When
multiple threads are executing at the same time, it is necessary to protect data from being accessed
and used simultaneously by multiple threads. Global variables and data that must be shared
between threads must be handled differently to ensure proper operation. LabWindows/CVI
provides several mechanisms for protecting data and passing data between threads.
To pass arrays of data between threads, you can use a thread safe queue. A thread safe queue is a
data array used to store data as it is being passed between threads. Thread safe queues can prevent
threads from waiting on each other by buffering the data as it is passed between threads. Specify
the size of the queue when you create the queue. The queue can be set up to automatically resize
when the queue is filled to prevent data loss. Thread safe queues can be event-based to trigger
another thread to read data from the queue when the queue contains a certain amount of data. The
data can be read directly into a buffer in the reading thread or through pointers to the data in the
thread safe queue.
A good example of using a thread safe queue is a multithreaded data acquisition application that
uses one thread for data acquisition and one thread for user interface. The data acquisition thread
can acquire data and add it to the queue. The user interface thread can retrieve data from the queue,
when a certain amount of data is in the queue, and send the data to a graph.

LabWindows/CVI Basics II Course Manual

5-12

ni.com

Lesson 5

Additional Topics

Thread Safe Queue Example


Application
1.
2.
3.
4.
5.

Create Thread Safe Queue (CmtNewTSQ)


Install TSQ Callback (CmtInstallTSQCallback)
Create Thread (CmtScheduleThreadPoolFunction)
Write Data
Thread 1
Read Data from TSQ
(CmtReadTSQData)

Read Level

Write Data to Queue


(CmtWriteTSQData)

TSQ

Thread Safe Queue Example


Use thread safe queues to communicate between any existing threads. Typically, a thread safe
queue is used to communicate between the main thread and another thread. In multithreaded
LabWindows/CVI programs, it is best to handle all user interface functions in the main thread.
To create and use a thread safe queue between the main thread and another thread, complete the
following steps:
1. Create the thread safe queue using CmtNewTSQ.
2. Use CmtInstallTSQCallback to install a callback function in the main thread to monitor the
thread safe queue. CmtInstallTSQCallback function is called when the amount of data in
the thread safe queue reaches a certain level. This callback specifies the callback function and
the read level for the queue. It is best that the size of the queue is a multiple of the read level.
3. Use CmtScheduleThreadPoolFunction to create the other thread that writes data to the
queue.
4. Inside the thread function that is running in the new thread, use CmtWriteTSQData to write
data to the queue.
5. When the queue is filled past the specified read level, the callback function in the main thread
receives an event. When this event is received, the main thread reads the data from the queue
with CmtReadTSQData.

National Instruments Corporation

5-13

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Exercise 5-2

OBJECTIVE

Time to complete: 20 min.

To complete an example application that uses a thread


safe queue to communicate data between threads

LabWindows/CVI Basics II Course Manual

5-14

ni.com

Lesson 5

Exercise 5-2
Objective:

Additional Topics

Using a Thread Safe Queue

To complete an example application that uses a thread safe queue to communicate


between threads.
Often data within a thread needs to be passed outside of the thread. This data
is critical data and generally needs to be protected from external processes
that can corrupt the data. One way to pass data outside a thread is to use a
global variable. Using a global variable can cause the data to be corrupted if
other threads try to access the data. Therefore using a global variable is not
the best solution, even though it is easy. One way to protect data that is being
transferred from a thread is to use a queue. LabWindows/CVI comes with a
set of functions to protect data using thread safe queues. Thread safe queues
enable data to be easily transferred between threads.
In this exercise, you will complete an example application that spawns a
thread that calculates a sine wave to be displayed on a chart. When a thread
safe queue receives data, an event is created to handle the data that has been
written to it. This exercise shows you how to create a callback function for
thread safe queues and how to develop an architecture to create advanced
multithreaded applications.
You must perform the following steps to create an application that uses
thread safe queues to protect critical data.
1. Create a thread safe queue.
2. Install a thread safe queue callback function.
3. Create the thread.
4. Using the thread write data to the thread safe queue.
5. Using the thread safe queue callback function read the data from the
thread.

Note Notice that creating a thread pool was not mentioned in the preceding steps.
The DEFAULT_THREAD_POOL that is created by LabWindows/CVI can contain up to
2 + 2 * (number of processors in computer) threads. In most computers with only
one processor there can be four threads running at any time. Most of the time it is not
necessary to create a new thread pool if the application requires only two or three threads.
If you do not know in advance how many threads the application will require, then it is a
good idea to create a new thread pool.

Part A: main Function


The main function needs to create the thread safe queue and install the
callback function for the thread safe queue. Complete the following steps to
modify the main function for the thread safe queue exercise.

National Instruments Corporation

5-15

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

1. Open the tsq.prj located in the directory C:\Exercises\CVI


Basics II\Lesson 5\tsq.prj. This project is partially completed
for you. The user interface, shown in the following figure, consists of a
panel with a strip chart and three command buttons: Start, Stop, and
Quit.
The Start button begins simulated data acquisition in a new thread. This
thread passes data back to the user interface thread through a thread safe
queue. The Stop button halts the simulated data acquisition thread. The
Quit button stops the simulated data acquisition, if necessary, and exits
the program. In this exercise, you add the functions to create and
communicate between threads.

2. Open tsq.c. Navigate to the main function. The following figure


shows the completed main function.

LabWindows/CVI Basics II Course Manual

5-16

ni.com

Lesson 5

Additional Topics

In the main function place your cursor below the /* Create Thread
Safe Queue */ comment. Insert the CmtNewTSQ function under the
comment to create a new thread safe queue before starting the user
interface. From the Library Tree, select Utility Library
MultithreadingThread Safe QueueGeneral Functions
CmtNewTSQ and complete the function panel as shown in the
following table.
Number of Items
Item Size
Options
Queue Handle

QUEUE_SIZE
sizeof(double)
0
&TSQHandle

Note After you complete the function panel, select CodeInsert Function Call to
insert the function call into your source code.

Use the constant QUEUE_SIZE for the number of items in the queue.
The queue holds double values, so the item size is sizeof(double).
Use the global variable TSQHandle, which is already declared in
tsq.c, for the thread safe queue handle.

National Instruments Corporation

5-17

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

3. Place your cursor below the /* Install callback function for


TSQ */ comment. Insert the CmtInstallTSQCallback function
under the comment. From the Library Tree, select Utility Library
MultithreadingThread Safe QueueCallbacks
CmtInstallTSQCallback and complete the function panel as shown in
the following table and insert the function call.
Queue Handle

TSQHandle

Event
Event Threshold Value
Callback Function
Callback Data
Callback Thread ID

Items in Queue

Callback ID

50
ReadDataFromTSQ
&callbackID
CmtGetCurrentThreadID()
&callbackID

This function installs the thread safe queue event callback function so
that when 50 items are in the queue, the ReadDataFromTSQ function is
called.
4. Place your cursor below the /* Uninstall the thread safe
queue callback function */ comment. Insert the
CmtUninstallTSQCallback function under the comment. From the
Library Tree, select Utility LibraryMultithreadingThread Safe
QueueCallbacksCmtUninstallTSQCallback and complete the
function panel as shown in the following table. Then, insert the function
call in the code.
Queue Handle
Callback ID

TSQHandle
callbackID

5. Add the following line of code below CmtUninstallTSQCallback


function, to set callbackID to 0.
callbackID = 0;

Setting callbackID to zero allows you to safely destroy the TSQ.


6. Discard the thread safe queue before the application exits by calling
CmtDiscardTSQ after the comment /* Discard Thread Safe
Queue */. Insert the CmtDiscardTSQ function under the comment.
From the Library Tree, select Utility LibraryMultithreading
Thread Safe QueueGeneral FunctionsCmtDiscardTSQ and
complete the function panel as shown in the following table.
Queue Handle

LabWindows/CVI Basics II Course Manual

TSQHandle

5-18

ni.com

Lesson 5

Additional Topics

Part B: Start Button Callback


The Start button callback function determines if the thread is running and
schedules the thread if the thread is not running. The following figure shows
the completed callback function for the Start button.

1. All of the code to determine if the thread is running has already been
written. It is always good practice to write code that checks to make sure
that the maximum number of threads for the application has not been
reached in the code that schedules the thread. Place your cursor below
the /* Create new thread to generate data by scheduling
function */ comment. Insert the
CmtScheduleThreadPoolFunction function under the comment.
From the Library Tree, select Utility LibraryMultithreading
ThreadPoolCall Scheduling Functions
CmtScheduleThreadPoolFunction and complete the function panel as
shown in the following table.
Pool Handle
Thread Function
Thread Function Data
Thread Function ID

DEFAULT_THREAD_POOL_HANDLE
SimulateData
&threadID
&threadID

This function schedules the SimulateData function in a thread. Notice


that the StartAcquisition function sets the runThread flag to 1.
The runThread flag is used to stop the thread from executing. Notice
that runThread was declared as volatile. All global variables that
will be accessed by a thread need to be declared as volatile.

National Instruments Corporation

5-19

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Part C: Thread Function


The function that will be scheduled in a thread for this application is called
SimulateData. The following figure shows the completed function.

1. The code for the function has already been written. This function creates
a random number that specifies the length of the sine wave to generate.
The only thing that you must do is send the sine data from the thread to
the main calling application. Remember that this data is critical data and
must be protected. Place your cursor below the /* Add the data in
the write buffer to the thread-safe queue */ comment.
Insert the CmtWriteTSQData function under the comment. From the
Library Tree, select Utility LibraryMultithreadingThread Safe
QueueReading/WritingCmtWriteTSQData and complete the
function panel as shown in the following table.
Queue Handle
Buffer
Number of Items
Timeout(ms)
Number of Items Flushed

TSQHandle
writeBuffer
numItemsInWriteBuffer
TSQ_INFINITE_TIMEOUT
NULL

The variables writeBuffer and numItemsInWriteBuffer have


already been declared. The timeout that is specified with
CmtWriteTSQData guarantees that the function waits until all of the
items have been written to the queue. Therefore, if there is not enough
space in the queue, the function waits.

LabWindows/CVI Basics II Course Manual

5-20

ni.com

Lesson 5

Additional Topics

Part D: Thread Safe Queue Event Callback Function


The ReadDataFromTSQ function is called when there has been a change to
the queue such as data being written to the queue. The function is a standard
event-based callback function that follows LabWindows/CVI event
handling capabilities. The following code shows the completed callback
function.

This function has already been written for you. Notice that the function
alternates between plot colors of red and blue each time the event function
is called. It is necessary to determine how many items are in the queue. This
is accomplished using the CmtGetTSQAttribute function. If an error
occurs, this function returns a negative number. CmtReadTSQData reads
the data from the queue. Notice how the function dynamically allocates an
array to store the data items from the queue.

Part E: Stop and Quit Button Callback Functions


Both the Stop and Quit button callback functions call the
StopAcqAndCleanup function, which sets the runThread flag to 0. This
causes the thread to stop execution. Once the thread has finished executing,
the thread and queue resources can be deallocated. The following figure
shows the completed code for the StopAcqAndCleanup function.

National Instruments Corporation

5-21

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Perform the following steps to complete the StopAcqAndCleanup


function.
1. Once the runThread flag has been set to 0, it is necessary to wait for
the thread to completely finish executing. The
CmtWaitForThreadPoolFunctionCompletion function waits for
the specified thread to complete. Insert this function below the /* Wait
for acquisition thread to exit */ comment. From the
Library Tree, select Utility LibraryMultithreadingThread Pool
Call Scheduling Functions
CmtWaitForThreadPoolFunctionCompletion and complete the
function panel as shown in the following table.
Pool Handle

DEFAULT_THREAD_POOL_HANDLE

Thread Function ID
Options

threadID
0

2. After the thread finishes executing, you can unschedule the thread
function from the thread pool. Insert the
CmtReleaseThreadPoolFunctionID function below the
CmtWaitForThreadPoolFunctionCompletion function. From the
Library Tree, select Utility LibraryMultithreadingThread Pool
Call Scheduling FunctionsCmtReleaseThreadPoolFunctionID and
complete the function panel as shown in the following table.
Pool Handle
Thread Function ID

LabWindows/CVI Basics II Course Manual

5-22

DEFAULT_THREAD_POOL_HANDLE
threadID

ni.com

Lesson 5

Additional Topics

Part F: Run
Save and run the program. Verify that the Start, Stop, and Quit buttons
work properly. Notice how the rate of data going to the strip chart changes
while the simulation is running. This action occurs because the data
simulation thread sends random sizes of data to the thread safe queue.
Notice that the application is passing data from the thread to the main
application to display the data on the strip chart. The data that is generated
in the SimulateData function will not get corrupted with the use of thread
safe queues.

End of Exercise 5-2

National Instruments Corporation

5-23

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Well-Behaved Applications

Well-Behaved Applications
If you spend much time inside a callback function, then periodically call ProcessSystemEvents
or ProcessDrawEvents. ProcessSystemEvents allows LabWindows/CVI to check if other
events, such as Windows messages, are waiting to be processed. ProcessDrawEvents updates
the user interface only. Refer to the messaging section of Lesson 1.
Use PostDeferredCall to execute functions after your callback has ended. The function does
not execute until the next call to GetUserEvent, RunUserInterface, or
ProcessSystemEvents.

LabWindows/CVI Basics II Course Manual

5-24

ni.com

Lesson 5

Additional Topics

Platform Software Development Kit (SDK)


The programmers interface to the Windows Server 2003/XP/2000/
NT 4.0/ Me/98/95 and 64-bit versions of Windows operating systems
A collection of import libraries, header files, utilities, code samples and helpa
collection of Windows APIs

All Windows applications rely on services that system DLLs provide


The Platform SDK is shipped with the LabWindows/CVI Full
Development System

Platform Software Development Kit (SDK)


The Platform Software Development Kit (SDK) is a collection of import libraries, header files, help
files, code samples and utility programs for Microsoft Windows operating system development.
These resources comprise the Windows API. The Platform SDK is a Microsoft term for the
interface to the core operating system components. Other SDKs are available for specific purposes,
such as DirectX and USB control, but the LabWindows/CVI Full Development System includes
the core libraries.
You can call Windows SDK functions in LabWindows/CVI. The LabWindows/CVI Full
Development System installer includes the option to install the Windows SDK, which allows you
to call all or a subset of the Windows SDK functions. The Platform SDK that is shipped with
LabWindows/CVI is the same for Windows 2000/XP. Select HelpWindows SDK to view online
help for the SDK functions.

National Instruments Corporation

5-25

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Benefits of Using SDK Functions


When you are familiar with the LabWindows/CVI libraries,
integrating the SDK directly is extremely powerful for
building Windows applications
Use SDK functions for tasks that you cannot do with the
LabWindows/CVI libraries
LabWindows/CVI SDK helps you get started with
pre-assembled basic projects and provides access to the
Windows help libraries

Benefits of Using SDK Functions


When you are familiar with the workings of LabWindows/CVI and know how to use external
libraries, you can expand the functionality by using the SDK functions directly. LabWindows/CVI
hides the complex procedure of standard Windows application development behind easy-to-use
library functions and a UI framework. However, for tasks that the core LabWindows/CVI libraries
do not support, use the SDK procedures to create almost any Windows application functionality.

LabWindows/CVI Basics II Course Manual

5-26

ni.com

Lesson 5

Additional Topics

Additional Functions
I/O and
Memory
Access

Using
Executables
Useful
Utilities
Creating
Well-Behaved
Applications

Error
Handling

Additional Functions
This lesson discusses additional functions that are useful for certain types of LabWindows/CVI
applications. However, many other functions are beyond the scope of this course. For these
functions, refer to the function panel help, help in the LabWindows/CVI Help, or the
LabWindows/CVI examples.

National Instruments Corporation

5-27

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

I/O and Memory Space


0xD000
ReadFromPhysicalMemory
inp
WriteToPhysicalMemory

0x378
outp

MapPhysicalMemory

pointer
UnMapPhysicalMemory

frees the resource

I/O and Memory Space


Typically, computer bus architectures have a chip enable line that toggles between I/O space and
memory space. Depending on the device you want to communicate with, you must select the proper
function.

I/O Space To communicate in I/O space, use the inp and outp functions. For example, to
perform any type of parallel port communication, you must use these functions. For these
functions, you should know the exact address to read from and write to.
Memory SpaceTo read from and write to physical memory, use
ReadFromPhysicalMemory and WriteToPhysicalMemory, respectively. You can use

extended versions of these functions to specify the actual byte transfer size. Every time you use
these functions, you are mapping and unmapping physical memory. To reduce this overhead,
use the MapPhysicalMemory/UnMapPhysicalMemory functions to obtain pointers to
portions of memory. You can treat these pointers like any other C pointers, incrementing and
manipulating objects in a familiar manner.
When you use Windows 2000/XP, these functions require you to load a low-level
support driver, cvintdrv.sys, that is shipped with LabWindows/CVI. The
LabWindows/CVI libraries automatically load the low-level support driver,
cvintdrv.sys, at startup if it is on disk. To ensure that the driver is loaded before you
proceed, call the CVILowLevelSupportDriverLoaded function at the beginning of
your program. To include the driver when creating your stand-alone executables, enable
the Low-Level Support Driver option in the Drivers & Components tab of the Edit
Installer dialog box.
Note

LabWindows/CVI Basics II Course Manual

5-28

ni.com

Lesson 5

Additional Topics

Memory Display Window


View and edit data in memory by address
Useful with pointers and direct memory access
View and edit data in various formats such as HEX, Dec, ASCII,
and so on

Memory Display Window


LabWindows/CVI provides tools to view variable values during debugging. These tools include
data tooltips, the Interactive Execution, and the Variables and Watch windows. When you write
directly to memory, however, you do not associate variables with the data you write. The only thing
you know about the data is the address in memory where the data was written. LabWindows/CVI
provides a Memory Display window, which you can use to view data in memory at any specified
address. You must provide the memory address in HEX format.
The WindowMemory command opens the Memory Display window in which you can view and
edit the memory of the program you are debugging. Use this window to view and edit the data in
hexadecimal (byte, word, long), decimal (byte, word, long), single-precision floating point,
double-precision floating point, or ASCII representation. You must enable the Edit Mode option
before you can modify the process memory. To change the value of a memory location, click that
cell in the Memory Display window and type the new value. You can drop variables onto the
Memory Display window. To drop variables onto the Memory Display window, select the variable
you want to view from the Source, Interactive Execution, Variables, or Watch window and drop it
onto the Memory Display window.
This window also can be useful with pointer data types. Often, the Variables and Watch windows
provide the memory location stored in the pointer. You also can use the Memory Display window
with that memory location to view the data in memory where the pointer is assigned.

National Instruments Corporation

5-29

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Source Code Browser


Cross-reference tool that lists selected files, functions,
variables, data types, and macros in a program
Identify program file interactions
Research definitions, declarations, call patterns, and functions
used
Easy to navigate list-based display

Source Code Browser


Another useful tool for debugging applications is the Source Code Browser, located under the
Window menu. The Source Code Browser is a multifunction display window that you can use to
search and view your program structures. Select which file contents to browse and click the various
list elements to search for the location where variables and functions are declared and used. To go
to the place in a file where a reference is located, double-click the reference in the Source Code
Broswer. LabWindows/CVI updates the Source Code Browser every time you compile your
program.

LabWindows/CVI Basics II Course Manual

5-30

ni.com

Lesson 5

Additional Topics

Handling Executables in LabWindows/CVI


LaunchExecutable(Ex)
RetireExecutableHandle
ExecutableHasTerminated
BeingDebuggedByCVI
TerminateExecutable
CheckForDuplicateAppInstance
system, ANSI C Library

Handling Executables in LabWindows/CVI


You can start an executable (*.exe) file programmatically from your application. With
LabWindows/CVI, you can run this executable, regardless of whether the executable was created
in LabWindows/CVI.
To start an executable, call LaunchExecutable and specify the executable file path. An extended
version of this function, LaunchExecutableEx, returns a handle to the executable. You can pass
this handle to other functions to determine if the executable is still running or to terminate the
executable. When you no longer need the handle, call RetireExecutableHandle.
ExecutableHasTerminated checks the status of the executable, and BeingDebuggedbyCVI
determines whether the current process is being debugged in LabWindows/CVI.
TerminateExecutable terminates an executable if the executable has not already terminated.
However, the best way to terminate an executable is to have a programmatic method to exit the
application in a known state. Use CheckForDuplicateAppInstance to stop LabWindows/CVI
from launching multiple instances of the same program.

A companion function to LaunchExecutable is system, an ANSI C function. The main


difference between the two is that system waits for the executable to finish before continuing with
the program.

National Instruments Corporation

5-31

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Error Handling
Library errors
SetBreakOnLibraryErrors
GetBreakOnLibraryErrors

Protection errors
SetBreakOnProtectionErrors
GetBreakOnProtectionErrors

Error Handling
LabWindows/CVI user protection allows the compiler to monitor all types of pointer
manipulations in your code and store data structures internally for each type. At run time,
LabWindows/CVI dynamically watches your pointer manipulations and informs you of illegal
accesses. LabWindows/CVI does the same action for simple out-of-bounds indexing of statically
declared arrays and more complex series of dynamic allocations with malloc, calloc, and so on.
With these user protection features, you do not need to spend time tracking down pointer bugs,
which are typically some of the most difficult bugs to find. LabWindows/CVI displays a run-time
dialog box that lists any instances of illegal access due to an out-of-bounds pointer or an attempt
to free an invalid pointer and highlights the erroneous line in your code. You can configure
LabWindows/CVI to display a run-time error dialog box and suspend execution when an NI library
function reports an error. To enable this type of debugging, select RunBreak onLibrary Errors
or use the Utility Library SetBreakOnLibraryErrors/GetBreakOnLibraryErrors
functions. You also can work around user protection errors flagged by LabWindows/CVI by using
the SetBreakOnProtectionErrors/GetBreakOnProtectionErrors functions. Normally,
you apply these functions around a small section of code as a workaround to some pointer problems
you have coded into your program.
LabWindows/CVI keeps track of all library function calls and watches all pointer accesses as it
executes your program and informs you when it detects an error. When you do not perform a debug
build, these features are disabled.

LabWindows/CVI Basics II Course Manual

5-32

ni.com

Lesson 5

Set Sleep Policy

Additional Topics

Sleep More

Do Not Sleep

Set Sleep Policy


SetSleepPolicy controls how much your application sleeps. Each time LabWindows/CVI

checks an event from the operating system, it can put itself in the background, in sleep mode, for
a specified period of time. While LabWindows/CVI is in sleep mode, other applications have more
processor time. The disadvantage of increasing the amount your application sleeps is that your
application responds slightly slower to events.
To view or change the current LabWindows/CVI sleep policy, select OptionsEnvironment.
CVI environment sleep policyYou can specify how much LabWindows/CVI sleeps by
selecting one of the following sleep policy choices:

Do not sleep

Sleep some

Sleep more

You also can view or change the sleep policy programmatically by calling either
GetSleepPolicy or SetSleepPolicy. By using SetSleepPolicy, you might free some
CPU use.
The figure above demonstrates the effect of the sleep policy on a Windows XP system. Changes in
sleep policy have different effects depending on the operating system. Experiment with the various
sleep options for your particular application. Increase the sleep mode if you want to free processor
usage and decrease the sleep mode if you want LabWindows/CVI to poll the user interface faster
for user events.

National Instruments Corporation

5-33

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Additional Functionality
Use <Ctrl-Shift-P>, Find Function Panel, to search for
functions based on keywords
Check out the built-in LabWindows/CVI instrument drivers
in the C:\Program Files\National
Instruments\CVI\toolslib directory
Increase your Windows programming skills with the
Windows SDK functions

Additional Functionality
Because of the large number of functions and utilities within LabWindows/CVI, it is important that
you know how to find the functions you need to complete or refine your application.
In the Source window, use the ViewFind Function Panel command (<Ctrl-Shift-P>) to search
for functions based solely on keywords. Remember to use a variety of synonyms, because the
function might be spelled differently than you expected.
LabWindows/CVI includes functionality through its built-in instrument drivers. As you learned in
this course, LabWindows/CVI provides many drivers for custom controls but also provides several
miscellaneous functions in the toolbox instrument driver. You can supplement the built-in
instrument drivers by purchasing add-on toolkits. Currently, you can purchase toolkits for SQL
(database manipulation), TX (test function management), SPC (statistical process control), IMAQ
(image processing), PID (process control for automation), and INET (internet).
If a function does not exist, you can create the function through Windows SDK. Creating a function
using the Windows SDK requires that you have some knowledge of Windows programming.

LabWindows/CVI Basics II Course Manual

5-34

ni.com

Lesson 5

Additional Topics

Toolkits
Enhance LabWindows/CVI through add-on toolkits:
TestStandtest management
SQLdatabase manipulation
PIDfeedback control
IMAQimage processing

Toolkits
As a stand-alone package, LabWindows/CVI includes a wealth of features. However, you can
enhance LabWindows/CVI with toolkits that include functions for specific business applications.
These toolkits are sold as separate packages because they include functionality that not all
LabWindows/CVI programmers need.
TestStand
TestStand is a ready-to-run, customizable test executive used in automated test environments. A
test executive relieves test engineers from worrying about the repetitive tasks of test program
management, such as logging test results to file and handling multiple levels of users. TestStand
allows a test engineering group to spend the bulk of its time on one specialized
purposedeveloping test functions.
SQL ToolkitInterfacing with Databases
With the Structured Query Language (SQL toolkit) LabWindows/CVI programs can manipulate
database files. Use the SQL toolkit to do basic database functions, such as creating, fetching, and
sorting records.
PID Toolkit
PID, Proportional-Integral-Derivative is a defined control strategy standard used in industry.
The PID toolkit is an instrument driver with functions to access the process parameters associated
with PID algorithms.
IMAQ Vision
IMAQ Vision is an add-on package for adding image processing and machine vision features to
your applications.

National Instruments Corporation

5-35

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Toolkits (cont.)
Enhance LabWindows/CVI through add-on toolkits:
Motion Controlmotion sequencing
SPCstatistical process control
Signal Processing Toolsetsignal processing and
spectral analysis

Toolkits (cont.)
Motion Control
The Motion Control Module for LabWindows/CVI provides an interactive development
environment for motion sequencing. The Motion Control Module integrates with NI vision, data
acquisition, and instrument control software and hardware.
SPC Toolkit
The SPC Toolkit contains functions to determine the statistics necessary for process
controldeviation, control limits, ranges, process capability.
Signal Processing Toolset
The Signal Processing Toolset is a software package that gives users ready-to-run, stand-alone
signal processing capabilities and developers high-level digital signal processing (DSP) tools and
utilities. The toolset provides four toolkits for digital filter design, joint time-frequency analysis,
wavelet and filter bank design, and super-resolution, model-based spectral analysis.
You can access all LabWindows/CVI toolkits through instrument drivers. Instrument drivers are
general tools for hiding low-level complexity, not just for controlling stand-alone instruments.
Though you purchase toolkits in addition to the LabWindows/CVI package, toolkits actually
reduce development costs. Before you start developing your application, calculate the time you
would spend creating the basic functionality that might already exist in the toolkits. Development
time builds quickly. In addition, the maintenance costs of in-house development are higher than
buying tools that you can customize.

LabWindows/CVI Basics II Course Manual

5-36

ni.com

Lesson 5

Additional Topics

Note There might be licensing issues regarding toolkits if you want to distribute
applications that use them.

National Instruments Corporation

5-37

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Summary Lesson 5
This lesson describes a wide variety of topics about the powerful
set of LabWindows/CVI features.
Multithreaded Programmingusing the threading tools of
LabWindows/CVI to create efficient programs
Platform SDKadding the power of Windows
programming to LabWindows/CVI
Utility functionsuncovering the depth of
LabWindows/CVI functions

Summary Lesson 5
This lesson describes an assortment of features that extend the basic functionality of
LabWindows/CVI.
To develop programs that take advantage of multiprocessor machines and can do multiple functions
at once, break the program into multiple threads using functions in the Multithreading class of the
Utility Library.
If you cannot find a particular way to accomplish an objective using LabWindows/CVI libraries,
you can integrate the Platform SDK into your applications.
The Utility Library provides several functions to meet specialized needs, such as handling
executables.

LabWindows/CVI Basics II Course Manual

5-38

ni.com

Lesson 5

Additional Topics

LabWindows/CVI Publications
LabWindows/CVI Programming for Beginners by Shahid F. Khalid
Advanced Topics in LabWindows/CVI by Shahid F. Khalid

LabWindows/CVI Publications
The books listed in the figure above are just a few of the publications written about
LabWindows/CVI programming and applications. The National Instruments Web site contains a
list of all the LabWindows/CVI books and links to locations where you can purchase these books.

National Instruments Corporation

5-39

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Continuing with National Instruments


LabWindows/CVI offers a flexible base for a wide variety of
programming needs
Our training and support extends to cover several of these
topics in more detail, including classes in the following topics:
Hardware courses such as Data Acquisition & Signal Conditioning
and Modular Instruments
TestStand
Instrument Driver Development
DIAdem
Online courses such as Machine Vision and LabVIEW Real-Time
Self-Paced: a variety of instructional packages and tools
designed to educate you at your own pace

Continuing with National Instruments


This lesson provides overviews of many modules and toolkits offered by NI.
Several of these packages are complete programming environments beyond the basic
LabWindows/CVI package. While this course is intended to get you started with your NI software,
it is by no means a comprehensive discussion.
If you are interested in these toolkits or other software environments, consider taking one of our
advanced topics classes. The courses listed in the figure above continue the training you received
in this course and expand it to other areas. You can purchase just the course materials or sign up
for an instructor-led hands-on course by contacting National Instruments.

LabWindows/CVI Basics II Course Manual

5-40

ni.com

Lesson 5

Additional Topics

Notes

National Instruments Corporation

5-41

LabWindows/CVI Basics II Course Manual

Lesson 5

Additional Topics

Notes

LabWindows/CVI Basics II Course Manual

5-42

ni.com

Additional Information and Resources

This appendix contains additional information about National Instruments


technical support options and LabWindows/CVI resources.

National Instruments Technical Support Options


Visit the following sections of the National Instruments Web site at ni.com
for technical support and professional services.

SupportOnline technical support resources at ni.com/support


include the following:

Self-Help ResourcesFor answers and solutions, visit the


award-winning National Instruments Web site for software drivers
and updates, a searchable KnowledgeBase, product manuals,
step-by-step troubleshooting wizards, thousands of example
programs, tutorials, application notes and instrument drivers.

Free Technical SupportAll registered users receive free Basic


Service, which includes access to hundreds of Application
Engineers worldwide in the NI Developer Exchange at
ni.com/exchange. National Instruments Application Engineers
make sure every question receives an answer.
For information about other technical support options in your area,
visit ni.com/services or contact your local office at
ni.com/contact.

System IntegrationIf you have time constraints, limited in-house


technical resources, or other project challenges, National Instruments
Alliance Partner members can help. The NI Alliance Partners joins
system integrators, consultants, and hardware vendors to provide
comprehensive service and expertise to customers. The program ensures
qualified, specialized assistance for application and system
development. To learn more, call your local NI office or visit
ni.com/alliance.

For more information, contact your local office or NI corporate


headquarters. Phone numbers for our worldwide offices are listed at the
front of this manual. You also can visit the Worldwide Offices section of
ni.com/niglobal to access the branch office Web sites, which provide
up-to-date contact information, support phone numbers, email addresses,
and current events.

National Instruments Corporation

A-1

LabWindows/CVI Basics II Course Manual

Appendix A

Additional Information and Resources

Other National Instruments Training Courses


National Instruments offers several training courses for LabWindows/CVI
users. These courses build on the training in this course and are the fastest
route to productivity with LabWindows/CVI. Visit ni.com/training to
purchase course materials or sign up for instructor-led, hands-on courses at
locations around the world.

National Instruments Certification


Earning an NI certification acknowledges your expertise in working with
NI products and technologies. The measurement and automation industry,
your employer, clients, and peers recognize your NI certification credential
as a symbol of the skills and knowledge you have gained through
experience. areas. Visit ni.com/training for more information about the
NI certification program.

LabWindows/CVI Resources
This section describes how you can receive more information regarding
LabWindows/CVI.

LabWindows/CVI Web Sites


ni.com/cvi/
ni.com/support/cvisupp/
ni.com/ivi/
ni.com/devzone/idnet/
ni.com/support/gpibsupp/
ni.com/support/gpib/versions/
ni.com/support/visasupp/

LabWindows/CVI Basics II Course Manual

A-2

ni.com

Course Evaluation
Course _______________________________________________________________________________________
Location _____________________________________________________________________________________
Instructor _________________________________________

Date ____________________________________

Student Information (optional)


Name ________________________________________________________________________________________
Phone ___________________________________

Company _________________________________________

Instructor
Please evaluate the instructor by checking the appropriate circle.

Unsatisfactory Poor

Satisfactory Good

Excellent

Instructors ability to communicate course concepts

Instructors knowledge of the subject matter

Instructors presentation skills

Instructors sensitivity to class needs

Instructors preparation for the class

Course
Training facility quality
Training equipment quality
Was the hardware set up correctly?
The course length was

Yes

No

Too long Just right Too short


Too much Just right Not enough

The detail of topics covered in the course was


The course material was clear and easy to follow.
Did the course cover material as advertised?

Yes

No

Sometimes

Yes No

I had the skills or knowledge I needed to attend this course.


Yes No If no, how could you have been
better prepared for the course? ____________________________________________________________________
_____________________________________________________________________________________________
What were the strong points of the course? __________________________________________________________
_____________________________________________________________________________________________
What topics would you add to the course? ___________________________________________________________
_____________________________________________________________________________________________
What part(s) of the course need to be condensed or removed? ____________________________________________
_____________________________________________________________________________________________
What needs to be added to the course to make it better? ________________________________________________
_____________________________________________________________________________________________
How did you benefit from taking this course? ________________________________________________________
_____________________________________________________________________________________________
Are there others at your company who have training needs? Please list. ____________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
Do you have other training needs that we could assist you with? _________________________________________
_____________________________________________________________________________________________
How did you hear about this course? NI Web site NI Sales Representative Mailing

Co-worker

Other _____________________________________________________________________________________

You might also like