Map Basic User Guide
Map Basic User Guide
10.5
USER GUIDE
Information in this document is subject to change without notice and does not represent a commitment on the part of the vendor or its representatives. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, without the written permission of Pitney Bowes Software Inc., One Global View, Troy, New York 12180-8399. 2010 Pitney Bowes Software Inc. All rights reserved. MapInfo, Group 1 Software, and MapBasic are trademarks of Pitney Bowes Software Inc. All other marks and trademarks are property of their respective holders. United States: Phone: 518.285.6000 Fax: 518.285.6070 Sales: 800.327.8627 Government Sales: 800.619.2333 Technical Support: 518.285.7283 Technical Support Fax: 518.285.6080 pbinsight.com Canada: Phone: 416.594.5200 Fax: 416.594.5201 Sales: 800.268.3282 Technical Support:.518.285.7283 Technical Support Fax: 518.285.6080 pbinsight.ca Europe/United Kingdom: Phone: +44.1753.848.200 Fax: +44.1753.621.140 Technical Support: +44.1753.848.229 pbinsight.co.uk Asia Pacific/Australia: Phone: +61.2.9437.6255 Fax: +61.2.9439.1773 Technical Support: 1.800.648.899 pbinsight.com.au Contact information for all Pitney Bowes Software Inc. offices is located at: http://www.pbinsight.com/about/contact-us. Adobe Acrobat is a registered trademark of Adobe Systems Incorporated in the United States. 1993 - 2009 Safe Software, Inc. libtiff 1988-1995 Sam Leffler, copyright Silicon Graphics, Inc. libgeotiff 2010 Niles D. Ritter. Portions 1999 3D Graphics, Inc. All Rights Reserved. HIL - Halo Image Library 1993, Media Cybernetics Inc. Halo Imaging Library is a trademark of Media Cybernetics, Inc. Portions thereof LEAD Technologies, Inc. 1991-2003. All Rights Reserved. Portions 1993-2010 Ken Martin, Will Schroeder, Bill Lorensen. All Rights Reserved. ECW by ER Mapper 1993-2010 VM Grid by Northwood Technologies, Inc., a Marconi Company 1995-2005. Portions 2010 Earth Resource Mapping, Ltd. All Rights Reserved. MrSID, MrSID Decompressor and the MrSID logo are trademarks of LizardTech, Inc. used under license. Portions of this computer program are copyright 1995-1998 LizardTech and/or the university of California or are protected by US patent nos. 5,710,835 or 5,467,110 and are used under license. All rights reserved. MrSID is protected under US and international patent & copyright treaties and foreign patent applications are pending. Unauthorized use or duplication prohibited. Contains FME Objects; 2010 Safe Software, Inc. Crystal Reports is proprietary trademark of Crystal Decisions. All Rights Reserved. Amyuni PDF Converter 2000-2007, AMYUNI Consultants AMYUNI Technologies. All rights reserved. Civic England - Public Sector Symbols Copyright 2010 West London Alliance. The symbols may be used free of charge. For more information on these symbols, including how to obtain them for use in other applications, please visit the West London Alliance Web site at http://www.westlondonalliance.org/ 1984-2010 Tele Atlas. All Rights Reserved. This material is proprietary and the subject of copyright protection and other intellectual property rights owned or licensed to Tele Atlas. The use of this material is subject to the terms of a license agreement. You will be held liable for any unauthorized copying or disclosure of this material. Microsoft Bing 2010 Microsoft Corporation May 2010
Table of Contents
Chapter 1: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Hardware & Software Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14 Compatibility with Previous Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15 Installing the MapBasic Development Environment . . . . . . . . . . . . . . . . . . . . . . . . . . .15 Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15 Starting MapBasic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15 MapBasic File Names and File Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15 MapBasic Documentation Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16 Conventions Used in This Manual. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17 Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17 Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17 Getting Technical Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 Contacting Technical Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 Software Defects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19 Other Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19
Compiling Your Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30 A Note on Compilation Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31 Running a Compiled Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31 Using Another Editor to Write MapBasic Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . .32 Linking Multiple Modules Into a Single Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33 What is a MapBasic Project File? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33 Creating a Project File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34 Compiling and Linking a Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35 Calling Functions or Procedures From Other Modules . . . . . . . . . . . . . . . . . . . . . . . . .36 Menu Summary in MapBasic Development Environment . . . . . . . . . . . . . . . . . . . . . . .37 The Edit Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38 The Search Menu. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38 The Project Menu. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39 The Window Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40 The Help Menu. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40
WhileWend Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63 Ending Your Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63 Ending Your Program and MapInfo Professional. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63 Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .64 Main Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .64 Calling a Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .64 Calling a Procedure That Has Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65 Passing Parameters By Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65 Passing Parameters By Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66 Calling Procedures Recursively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66 Procedures That Act As System Event Handlers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67 What Is a System Event?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67 What Is an Event Handler? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67 When Is a System Event Handler Called? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .69 Tips for Handler Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70 Keep Handler Procedures Short . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70 Selecting Without Calling SelChangedHandler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70 Preventing Infinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70 Custom Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71 Scope of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71 Compiler Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72 The Define Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72 The Include Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72 Program Organization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73
Removing Items From A Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84 Creating A New Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .85 Altering A Menu Item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .86 Re-Defining The Menu Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87 Specifying Language-Independent Menu References . . . . . . . . . . . . . . . . . . . . . . . . . .88 Customizing MapInfo Professionals Shortcut Menus . . . . . . . . . . . . . . . . . . . . . . . . . .88 Assigning One Handler Procedure To Multiple Menu Items . . . . . . . . . . . . . . . . . . . . .89 Simulating Menu Selections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90 Defining Shortcut Keys And Hot Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90 Controlling Menus Through the MapInfo Professional Menus File . . . . . . . . . . . . . . . .91 Standard Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93 Displaying a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93 Asking a Yes-or-No Question. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93 Selecting a File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93 Indicating the Percent Complete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .94 Displaying One Row From a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .94 Custom Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95 Sizes and Positions of Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95 Control Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .96 Specifying a Controls Initial Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .99 Reading a Controls Final Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100 Responding to User Actions by Calling a Handler Procedure . . . . . . . . . . . . . . . . . . .100 Enabled / Disabled Controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101 Letting the User Choose From a List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101 Managing MultiListBox Controls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102 Specifying Shortcut Keys for Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102 Closing a Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103 Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103 Specifying a Windows Size and Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .104 Map Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .104 Using Animation Layers to Speed Up Map Redraws . . . . . . . . . . . . . . . . . . . . . . . . . .105 Browser Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107 Graph Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .107 Layout Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .108 Redistrict Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .108 Message Window. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .108 ButtonPads (Toolbars) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110 What Happens When the User Chooses a Button?. . . . . . . . . . . . . . . . . . . . . . . . . . .110 MapBasic Statements Related To ButtonPads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .111 Creating A Custom PushButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .112 Adding A Button To The Main ButtonPad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .113
MapBasic 10.5 6 User Guide
Creating A Custom ToolButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .113 Choosing Icons for Custom Buttons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .114 Selecting Objects by Clicking With a ToolButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115 Including Standard Buttons in Custom ButtonPads . . . . . . . . . . . . . . . . . . . . . . . . . . .116 Assigning Help Messages to Buttons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .117 Docking a ButtonPad to the Top of the Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .118 Other Features of ButtonPads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .118 Integrating Your Application Into MapInfo Professional . . . . . . . . . . . . . . . . . . . . . . .118 Loading Applications Through the Startup Workspace . . . . . . . . . . . . . . . . . . . . . . . .119 Manipulating Workspaces through MapBasic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119 Performance Tips for the User Interface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120 Animation Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120 Avoiding Unnecessary Window Redraws . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120 Purging the Message Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121 Suppressing Progress Bar Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121
Preventing Conflicts When Writing Shared Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138 Opening a Table for Writing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .140 Files that Make Up a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .140 Raster Image Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .140 Working With Metadata. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .142 What is Metadata? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .142 What Do Metadata Keys Look Like? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .142 Examples of Working With Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .143 Working With Seamless Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .145 What is a Seamless Table? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .145 How Do Seamless Tables Work? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .145 MapBasic Syntax for Seamless Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .146 Limitations of Seamless Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .146 Accessing DBMS Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .147 How Remote Data Commands Communicate with a Database . . . . . . . . . . . . . . . . .147 Connecting and Disconnecting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .147 PostGIS Geometry Conversion Behavior. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149 Accessing/Updating Remote Databases with Linked Tables . . . . . . . . . . . . . . . . . . .149 Live Access to Remote Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150 Performance Tips for Table Manipulation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150 Set the Default View for Remote Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150 Minimize Transaction-File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151 Use Indices Where Appropriate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151 Using Sub-Selects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151 Optimized Select Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151 Using Update Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .152
Style Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .166 Selecting Objects of a Particular Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .167 Creating New Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .169 Object-Creation Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .169 Object-Creation Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .170 Creating Objects With Variable Numbers of Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . .170 Storing Objects In a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .171 Creating Objects Based On Existing Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 Creating a Buffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 Using Union, Intersection, and Merge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 Creating Isograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .173 Creating Offset Copies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .173 Modifying Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .174 General Procedure for Modifying an Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .174 Repositioning An Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .174 Moving Objects and Object Nodes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .174 Modifying An Objects Pen, Brush, Font, or Symbol Style . . . . . . . . . . . . . . . . . . . . . .174 Converting An Object To A Region or Polyline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .175 Erasing Part Of An Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .175 Points Of Intersection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .176 Working With Map Labels. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .176 Turning Labels On . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .176 Turning Labels Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .176 Editing Individual Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .176 Querying Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177 Other Examples of the Set Map Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177 Differences Between Labels and Text Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .178 Coordinates and Units of Measure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .180 Units of Measure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .181 Advanced Geographic Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .182 Using Geographic Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .182 Querying Objects in Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .184 Using Geographic SQL Queries With Subselects . . . . . . . . . . . . . . . . . . . . . . . . . . . .184 Using Geographic Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .185 Proportional Data Aggregation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .186
User-Defined Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .190 Logical Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .190 Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .191 Example: Calling a Routine in KERNEL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .191 Troubleshooting Tips for DLLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .192 Creating Custom Button Icons and Draw Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . .193 Reusing Standard Icons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193 Custom Icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .194 Custom Draw Cursors for Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .195 Inter-Application Communication Using DDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .195 Overview of DDE Conversations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .195 How MapBasic Acts as a DDE Client. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .196 How MapInfo Professional Acts as a DDE Server . . . . . . . . . . . . . . . . . . . . . . . . . . . .197 How MapInfo Professional Handles DDE Execute Messages . . . . . . . . . . . . . . . . . . .199 Communicating With Visual Basic Using DDE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .200 Examples of DDE Conversations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .200 DDE Advise Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .200 Incorporating Windows Help Into Your Application . . . . . . . . . . . . . . . . . . . . . . . . . .201
Disabling Online Help. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .220 Displaying a Custom Help File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .220 Related MapBasic Statements and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .221 OLE Automation Object Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .223 Using the OLE Object Model from within the MapInfo Professional Process . . . . . . .225 Properties of the Application Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .225 Properties of the DockWindow Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .228 Properties of the MBApplications Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .231 Properties of an Object in MBApplications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .231 Properties of the MBGlobals Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .232 Properties of an Object in MBGlobals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .233 Properties of the MIMapGen Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .234 Methods of the MIMapGen Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .235 Properties of the MISearchInfo Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .236 Method of the MIRow Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .237 Properties of the MIField Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .237 Properties of the MISelection Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .238 MapInfo Professional Command-Line Arguments. . . . . . . . . . . . . . . . . . . . . . . . . . . .239 Getting Started with Integrated Mapping and Visual C++ with MFC . . . . . . . . . . . . . .240 Adding Toolbar Buttons and Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243 Using Exception Handling to Catch MapInfo Professional Errors . . . . . . . . . . . . . . . .245 Add OLE Automation Server Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .246 Adding the WindowContentsChanged Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247 Learning More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247
Accessing MapInfo Professional through COM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .262 Callback Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .263 Thread Safety Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .265
Appendix C: Supported ODBC Table Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 Appendix D: Making a Remote Table Mappable . . . . . . . . . . . . . . . . . . . . . . . . . 282
Creating a MapInfo Map Catalog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .283
MapBasic 10.5
12
User Guide
Getting Started
Welcome to the MapBasic Development Environment, the powerful, yet easyto-use programming language that lets you customize and automate MapInfo Professional. The following pages tell you what you need to know to install the MapBasic software. For information on the purpose and capabilities of MapBasic, see A Quick Look at MapBasic.
Whats New
New in this release of MapBasic: Added support for docking windows, see Properties of the DockWindow Object on page 228. Added two new methods related to docking windows to Properties of the Application Object on page 225: Method Name IDispatch* RegisterDockWindow(HWND hwnd, long domainId) Functionality Registers the given window with MapInfo Professional and returns an object that represents the docked window. During this call the dock window is created and docked to the default position. Calls to Dock and Float methods can be used to set a custom dock state for the window. The domainId argument only useful if you are using the COM API directly from your .Net code. In this case you should pass in the id of the current AppDomain. Unregisters the dock window specified by the dockWindow void UnregisterDockWindow(IDispat argument. Attempts to interact with the DockWindow object after it is unregistered will result in an error. ch* dockWindow)
Any display adapter supported by Windows Any mouse or pointing device supported by Windows 10 MB
MapBasic 10.5
14
User Guide
Installation
The MapBasic development environment is free. You can download a copy of MapBasic from the Pitney Bowes Software Inc. web site, at http://www.pbinsight.com, by selecting Support > Product Downloads and then clicking the MapBasic link. There is also information there about building custom applications and integrating MapInfo Professional into your application using the MapBasic development environment, go to http://go.pbinsight.com/mapbasicdocs.
Starting MapBasic
To start the MapBasic Development Environment either: Double-click the MapBasic icon on your desktop. From the Start menu, select MapBasic 10.0 from the Selected Program folder. You can check for product updates to your version anytime by selecting Help > Check for Update.
MapBasic 10.5
15
User Guide
Chapter 1: Getting Started MapBasic Documentation Set File Name mapbasic.chm mapbasic.def mapbasic.exe mapbasic.h MapBasic on-line help file. Include file containing standard define codes. executable file which runs the MapBasic development environment. Header file for C/C++ programmers; contents similar to mapbasic.def, but using C/C++ syntax. Part of the software; contains shared libraries. Part of the software; contains resources such as strings and dialog boxes. Include file containing menu-related define codes. Part of the software; contains shared executables. Include file for use by MapBasic application developers. It contains defines for use with printer control MapBasic statements. Contains sample programs. Contains log of installation process. Description
As you use the MapBasic development environment, you produce files with the following extensions: File Name filename.mb filename.mbx filename.mbp filename.mbo filename.err Program files (source code) Compiled (executable) files Project files (which list all modules to include in a project) Object files (files created after compiling modules in a project) Error listings, generated if you compile a program that has compilation errors. Description
MapBasic 10.5
16
User Guide
Chapter 1: Getting Started Conventions Used in This Manual View these documents online at http://go.pbinsight.com/mapbasicdocs. View them locally on your machine. These documents install with MapInfo Professional and are accessible from the MapInfo\Professional\Documentation folder (see MapBasicUserGuide.pdf and MapBasicReference.pdf in this folder).
Terms
This manual addresses the application developer as you, and refers to the person using an application as the user. For example: You can use MapBasics Note statement to give the user a message. The terms program and application are used in the following manner: A program is a text file typed in by you, the programmer. Typically, MapBasic program files have the extension .MB. An application file is a binary file executable by MapInfo Professional. The application file must be present when the user runs the application. MapBasic creates the application file when you compile your program. MapBasic application files typically have the extension .MBX (MapBasic eXecutable). A command is an item that you choose from a menu. For example, to open a file, choose the Open command from the File menu. A statement is an instruction you can issue from a MapBasic program. For example, a MapBasic program can issue a Select statement to select one or more rows from a table.
Typographical Conventions
The Courier font shows sample MapBasic program statements: Note "hello, world!" Bold Capitalization identifies MapBasic keywords: The Stop statement is used for debugging purposes. In the examples that appear in this manual, the first letter of each MapBasic language keyword is capitalized. However, you are not required to use the same capitalization when you type in your own programs. If you prefer, you can enter your programs using upper case, lower case, or mixed case. References to menu commands in the MapBasic development environment use the greater-than sign (>), as in the following example: Choose the File > New command to open a new edit window.
The expression File > New refers to the New command on the File menu.
MapBasic 10.5
17
User Guide
MapBasic 10.5
18
User Guide
Chapter 1: Getting Started Getting Technical Support 5. A brief explanation of the problem. Some details that can be helpful in this context are: Error messages Context in which the problem occurs Consistency - is the problem reoccurring or occurring erratically?
Software Defects
If the issue is deemed to be a bug in the software, the representative will log the issue in Pitney Bowes Software Inc. bug database and provide you with an incident number that you can use to track the bug. Future upgrades and patches have fixes for many of the bugs logged against the current version.
Other Resources
MapInfo-L Archive Database
Pitney Bowes Software Inc., in conjunction with Bill Thoen, provides a web-based, searchable archive database of MapInfo-L postings. The postings are currently organized by Discussion Threads and Postings by Date. Disclaimer: While Pitney Bowes Software Inc. provides this database as a service to its user community, administration of the MapInfo-L mailing list is still provided by Bill Thoen. More information on MapInfo-L can be obtained at the MapInfo-L web page located at http://www.directionsmag.com/mapinfo-l/.
MapBasic 10.5
19
User Guide
MapBasic is a software package that lets you customize and automate the MapInfo Professional desktop-mapping software.
Getting Started
The MapBasic software provides you with a development environment. Using this development environment, you can write programs in the MapBasic programming language. The MapBasic development environment includes: A text editor you can use to type your programs. If you already have a text editor you would rather use, you can use that editor instead of the MapBasic text editor. For details, see Using the Development Environment on page 26. The MapBasic compiler. After you have written a program, compile it to produce an executable application (specifically, an application that can be run by MapInfo Professional). The MapBasic linker. If you are creating a large, complex application, you can divide your program into separate modules, then link those modules together into one application. MapBasic online help, providing reference information for each statement and function in the MapBasic language. From looking at the name, you might expect the MapBasic programming language to be reminiscent of traditional BASIC languages. In fact, MapBasic programs do not look much like traditional BASIC programs. MapBasic does, however, bear a resemblance to newer versions of BASIC which have been developed in recent years (for example, Microsofts Visual Basic language). A Traditional BASIC Code Sample 20 30 40 50 60 80 GOSUB 3000 IF DONE = 1 THEN GOTO 90 FOR X = 1 TO 10 GOSUB 4000 NEXT X GOTO 30 A MapBasic Code Sample Call Check_Status(quit_time) Do While Not quit_time For x = 1 To 10 Call Process_batch(x) Next Loop
Every MapBasic program works in conjunction with MapInfo Professional. First, you use the MapBasic development environment to create and compile your program; then you run MapInfo Professional when you want to run your program. Thus, a MapBasic program is not a stand-alone program; it can only run when MapInfo Professional is running. You could say that a MapBasic program runs on top of MapInfo Professional. However, MapBasic is not merely a macro language, MapBasic is a full-featured programming language, with over 300 statements and functions. Furthermore, since MapBasic programs run on top of MapInfo Professional, MapBasic is able to take advantage of all of MapInfo Professionals geographic data-management capabilities.
Chapter 2: A Quick Look at MapBasic What Are the Key Features of MapBasic? 2. Choose File > New to open an edit window. 3. Type a MapBasic program into the edit window. If you do not have a program in mind, you can enter the following one-line MapBasic program: Note "Welcome to MapBasic!" 4. Choose File > Save to save the program to a file. Enter a file name such as welcome.mb. Do not close the Edit window. 5. Choose Project > Compile Current File. MapBasic compiles your program (welcome.mb) and creates a corresponding executable application file (welcome.mbx). 6. Run MapInfo Professional. 7. Choose Tools > Run MapBasic Program. MapInfo Professional prompts you to choose the program you want to run. 8. Select welcome.mbx to run your program display the message, Welcome to MapBasic! in a dialog box. Those are the main steps involved in creating, compiling, and running a MapBasic application. In practice, of course, the process is more complex. For example, the procedure outlined above does not describe what happens if you encounter a compilation error. For more details on creating and compiling MapBasic programs, see Using the Development Environment.
MapBasic 10.5
22
User Guide
MapBasic 10.5
23
User Guide
Chapter 2: A Quick Look at MapBasic The MapBasic Window in MapInfo Professional Sample Programs Many programmers find that the best way to learn a programming language is to study sample programs. Accordingly, MapBasic comes with a library of sample programs. See the Samples directory installed on your MapBasic CD or download for sample programs included with MapBasic. The MapBasic User Guide frequently refers to the TextBox sample program (textbox.mb). You may want to become familiar with this program before you learn MapBasic. MapInfo Workspace Files MapInfo Professional can save session information (for example, the list of what tables and windows are open) in a workspace file. If you use a text editor to examine a workspace file, you will see that the workspace contains MapBasic statements. You can copy MapBasic statements out of a workspace file, and paste the statements into your program. In a sense, any MapInfo workspace is a sample MapBasic program. For example, suppose you want to write a MapBasic program that creates an elaborate page layout. You could create the page layout interactively, using MapInfo Professional, and save the layout in a MapInfo workspace file. The workspace file would contain a set of MapBasic statements relating to page layouts. You then could copy the layout-related statements from the workspace file, and paste the statements into your MapBasic program. Online Help The MapBasic development environment provides extensive online Help. Much of the online Help is reference information, providing descriptions of every statement and function in the language. The Help file also provides instructions on using the MapBasic development environment. As you are typing in your program, if you select a statement or function name and press F1, the Help window shows you help for that statement or function. The Help system contains many brief sample programs which you can copy from the Help window and paste into your program. You can copy text out of the Help window by clicking and dragging within the Help window. If you are viewing a Help screen and you click on a MapBasic menu or a MapBasic edit window, the Help window disappears. This is standard behavior for Windows Help. The Help window has not been closed, it is simply in the background. Note that you can return to the Help window by pressing Alt-Tab. You can also prevent the Help window from disappearing by checking the Help windows Help > Always on Top menu item.
Chapter 2: A Quick Look at MapBasic The MapBasic Window in MapInfo Professional 2. Choose Options > Show MapBasic Window. The MapBasic window appears on the screen. Thereafter, as you use MapInfo Professionals menus and dialog boxes, the MapBasic window displays corresponding MapBasic statements. For example, if you perform a query by using MapInfo Professionals Select dialog box, the MapBasic window automatically shows you how you could perform the same operation through statements in the MapBasic language. You can also enter statements directly into the MapBasic window, although not all MapBasic statements may be executed in this manner. To determine if a statement may be issued through the MapBasic window, consult the MapBasic Reference and the online Help System. Statements that are not supported through the MapBasic window are identified by a notice that appears under the Restrictions heading. As a general rule, you cannot enter flow-control statements (for example, ForNext loops) through the MapBasic window. The MapBasic window is also a debugging tool. For details, see Debugging and Trapping Runtime Errors.
MapBasic 10.5
25
User Guide
The MapBasic software includes a text editor you can use to type your program. Conventional menu items (for example, Undo, Copy, Paste) make it easy to edit your program. Other menu items let you compile (and, optionally link) your program(s) into executable form. Online help for the MapBasic language is available as well. The MapBasic text editor, MapBasic compiler, and MapBasic online help are collectively known as the Development Environment.
MapBasic 10.5
27
User Guide
Keyboard Shortcuts
The following table lists the keyboard shortcuts you can use within the MapBasic edit window. Keyboard Action Home / End Ctrl-Home/ Ctrl-End Ctrl-TAB/ Ctrl-Shift-TAB Ctrl-T Ctrl-O Ctrl-N Ctrl-S Ctrl-P Ctrl-A Ctrl-C Ctrl-X Ctrl-V Ctrl-Del Del Ctrl-F Ctrl-G Ctrl-R Effect of Action Insertion point moves to beginning/end of line. Insertion point moves to beginning/end of document. Insertion point moves backward/forward one word.
Displays the Go To Line dialog box. Displays the Open dialog box. Opens a new, empty edit window. Saves the active edit window. Prints the active edit window. Selects all text in the edit window. Copies selected text to the clipboard. Cuts selected text and copies it to the clipboard. Pastes text from the clipboard into the edit window. Deletes the word after the insertion point. Deletes selected text; does not copy to clipboard. Displays the Find And Replace dialog box. Repeats the most recent Find command. Replaces the selected text (using the replacement text from the Find And Replace dialog box), and performs another Find. Displays Select Project File dialog box. Compiles the program in the active window. Next Error command; scrolls the edit window to show the line that caused a compilation error. Links the active project. Sends message to MapInfo Professional to run the active program.
Ctrl-L Ctrl-U
MapBasic 10.5
28
User Guide
Chapter 3: Using the Development Environment Editing Your Program Keyboard Action F1 F8 Ctrl-F4 Alt-F4 Shift-F4 Shift-F5 Displays Help. Displays Text Style dialog box, allowing you to change the font. Closes the active edit window. Exits the MapBasic development environment. Tile windows. Cascade windows. Effect of Action
If you select a function name before pressing F1, Help shows a topic describing that function.
Mouse Shortcuts
Mouse Action Double-click Effect of Action Double-clicking on text within your program selects a word. Double-clicking in the list of error messages scrolls the window to show the line of your program that caused the error. Highlights entire line of text (32-bit version only). Dragging text to another window copies the text. Dragging text within the same window moves the text (unless you hold down the Ctrl key during the drag, in which case the text is copied).
The MapBasic online help contains code samples. You can drag & drop code samples from the help window to your edit window. To drag and drop code samples from the Help window to your Edit window: 1. Display help. 2. Click and drag within the help window to highlight the text you want to copy. 3. Click on the text you highlighted. Without releasing the mouse button, drag the text out of the help window. 4. Move the mouse pointer over your edit window, and release the mouse button. The text is dropped into your program.
MapBasic 10.5
29
User Guide
MapBasic 10.5
30
User Guide
Chapter 3: Using the Development Environment Compiling Your Program Figure: First.mb
If you double-click an error message that appears beneath the edit window, MapBasic scrolls the window to show you the line of the program that caused the error. After you correct any errors in your program, choose Compile Current File again to try to recompile. Once your program compiles successfully, MapBasic displays a dialog box indicating that compilation was complete. When compilation is successful, MapBasic creates an .mbx file (MapBasic eXecutable). This .mbx file must be present to run the finished application. Thus, if you want to provide your users with a finished MapBasic application, but you do not want to give them all of your source code, give the users your .mbx file but not your .mb file.
MapBasic 10.5
31
User Guide
Chapter 3: Using the Development Environment Compiling Your Program The MapBasic development environment also provides a shortcut to running your program: After compiling your program, choose Run from MapBasics Project menu (or press Ctrl-U). MapBasic sends a message to MapInfo Professional, telling MapInfo Professional to execute the application. MapInfo Professional must already be running.
MapBasic 10.5
32
User Guide
Chapter 3: Using the Development Environment Linking Multiple Modules Into a Single Project If the command line includes the parameter -L followed by one or more project file names, MapBasic links the projects. (Linking and Project files are discussed in Compiling and Linking a Project on page 35.) For example, the following command line links the TextBox application: mapbasic -L tbproj.mbp The command line can include both the -D and the -L parameters, as shown below: mapbasic -D textbox.mb -L tbproj.mbp If you launch MapBasic with a command line that includes the -D parameter or the -L parameter, MapBasic shuts down after compiling or linking the appropriate files. To start MapBasic without displaying a splash screen use the -Nosplash parameter: mapbasic -Nosplash
MapBasic 10.5
33
User Guide
Chapter 3: Using the Development Environment Linking Multiple Modules Into a Single Project
MapBasic 10.5
34
User Guide
Chapter 3: Using the Development Environment Linking Multiple Modules Into a Single Project Module=C:\MB\CODE\CUSTOM.MBO Module=Local:MapBasic:custom.mbo Module=/MapBasic/mb_code/custom.mbo Note the extension on the filename; MapBasic object files have the file extension .mbo. MapBasic creates an object file when you compile a single module that is part of a multiplemodule project. Whenever you choose Project > Compile Current File, MapBasic tries to compile the current file into an executable application file (ending with .mbx). However, if the program file contains calls to functions or procedures that are not in the file, MapBasic cannot create an .mbx file. In this case, MapBasic assumes that the program is part of a larger project. MapBasic then builds an object file (.mbo) instead of an executable file (.mbx). MapBasic also creates an object file whenever the module that you are compiling does not have a Main procedure. 5. Repeat step 2 for every file you wish to include in your application. 6. Choose File > Save As to save the project file. In the Save As dialog box, choose the file type Project File (from the list of file types in the lower left corner of the dialog box), so that the file has the extension .mbp (MapBasic Project). 7. Close the edit window (either choose File > Close or click on the windows close box). If you add more modules to the project at a later date, remember to add appropriate Module= lines to the project file.
2. Choose Project > Select Project File to tell MapBasic which project file you want to link. The Select Project File dialog box displays. 3. Choose the project (.mbp) file you want, and click OK. The selected project file appears in an edit window. This file remains selected until you exit MapBasic, close the project files edit window, or choose the Project > Select Project File command again. Only one project file can be selected at any time. You cannot change which project file is selected by making an edit window the front-most window. You cannot change which project file is selected by choosing File > Open. To select the project file you want to link, choose Project > Select Project File. 4. Choose Project > Link Current Project to link your application. MapBasic reads the object (.mbo) files listed in the project file. If there are no link errors, MapBasic builds an executable (.mbx) file. If there are link errors, MapBasic displays an error message. You also can link a project in a single step, without first displaying the project file in an edit window, by choosing File > Link From File.
MapBasic 10.5 35 User Guide
Chapter 3: Using the Development Environment Linking Multiple Modules Into a Single Project The object files created by the MapBasic compiler cannot be linked using any other linker, such as a C-language linker. Only the MapBasic linker can link MapBasic object modules.
Chapter 3: Using the Development Environment Menu Summary in MapBasic Development Environment Global variables also allow you to share information with other applications that are running.
MapBasic 10.5
Chapter 3: Using the Development Environment Menu Summary in MapBasic Development Environment edit window.) Use Compile From File to compile a program written in another text editor. If there are compilation errors, Compile From File writes error messages to a text file named filename.err. To view the errors file, choose File > Open. Link From File links an existing project without first displaying the contents of the project file in an edit window. (As opposed to the Link Current Project command on the Project menu, which links the current project.) Page Setup defines printer options (for example, paper size and orientation). Print prints the active edit window. Print is available when there is at least one Edit window open. Exit exits the MapBasic environment. MapBasic prompts you to either save or discard any changes that have not been saved.
MapBasic 10.5
Chapter 3: Using the Development Environment Menu Summary in MapBasic Development Environment Find Again finds the next occurrence of the string specified in the previous Find dialog box. Find Again is available when there is at least one open edit window, and a Find operation has been performed. Replace And Find Again replaces the selected text with text specified in the Find dialog box, then finds and highlights the next occurrence of the search string. Next Error is a feature of the compiler that helps you correct syntax errors. When a program does not compile correctly, MapBasic displays a list of the errors at the bottom of the edit window. Next Error scrolls forward through the edit window, to the line in your program which corresponds to the next error in the error list. Next Error is available when there are error messages in the active edit window. Previous Error is similar to Next Error. Previous Error scrolls backward through the edit window to the previous item in the error list. Previous Error is available when there are error messages relating to the active edit window. Go To Line prompts you to type in a line number, then scrolls through the edit window to that line in your program. A program may compile successfully, yet it may encounter an error at runtime. When this happens, a dialog box appears, indicating that an error occurred at a certain line in your program. Typically, you then want to return to the MapBasic development environment and go to the appropriate line of your program. Go To Line is available when there is at least one edit window open.
To replace all occurrences of a text string: Type the replacement string in the Replace With text box, and click the Replace All button. MapBasic replaces all occurrences of the Find string with the Replace With string. This replacement happens instantly, with no confirmation prompt. To confirm each string replacement: 1. Choose Search > Find. The Find dialog box appears. 2. Fill in the Find and Replace With text boxes. 3. Within the Find dialog box, click the Find button. MapBasic finds and highlights the next occurrence of the text string. To replace the currently-highlighted string, press Ctrl-R (the hot-key for the Replace And Find Again menu command). If you do not want to replace the currently-highlighted occurrence of the Find string, press Ctrl-G (the hot-key for the Find Again menu command).
MapBasic 10.5
Chapter 3: Using the Development Environment Menu Summary in MapBasic Development Environment Compile Current File compiles the program in the active edit window. Compile Current File is available if there is at least one open edit window. If the compiler detects syntax errors in the program, MapBasic displays a list of errors at the bottom of the edit window. If there are no syntax errors, MapBasic builds an mbx file (if the module is a stand-alone program) or an object module (mbo) file. Link Current Project links the modules listed in the current project file, and produces an executable application file (unless there are errors, in which case an error message displays). Link Current Project is available whenever a project file is open. Run sends a message to the MapInfo Professional software, telling it to execute the application in the front-most edit window. Get Info displays statistics about the program in the active edit window. Get Info is available if there is at least one open edit window. Show/Hide Error List activates or deactivates the error list associated with the active edit window. If the error list is currently displayed, the menu item reads Hide Error List. If the error list is currently hidden, the menu item reads Show Error List. Show/Hide Error List is available when there is an open edit window with associated error messages.
MapBasic 10.5
40
User Guide
Chapter 3: Using the Development Environment Menu Summary in MapBasic Development Environment About MapBasic displays the About dialog box, which shows you copyright and version number information. Many of the help screens contain brief sample programs. You can copy those program fragments onto the clipboard, then paste them into your program. To copy text from a help screen, choose Edit > Copy from the help windows Edit menu or by dragging text directly out of the help window, and drop it into your program.
MapBasic 10.5
41
User Guide
MapBasic Fundamentals
Every MapBasic programmer should read this chapter, which describes many fundamental aspects of the MapBasic programming syntax.
Comments
In MapBasic, as in some other BASIC languages, the apostrophe character () signifies the beginning of a comment. When an apostrophe appears in a program, MapBasic treats the remainder of the line as a comment, unless the apostrophe appears within a quoted string constant.
Case-Sensitivity
The MapBasic compiler is case-insensitive. You can enter programs with UPPER-CASE, lowercase, or Mixed-Case capitalization. For clarity, this manual capitalizes the first letter of each MapBasic language keyword. Program variables appear in lower-case. For example, in the following program sample, the words If and Then have proper capitalization because they are keywords in MapBasic, whereas the word counter appears in lower-case, because it is the name of a variable. If counter > 5 Then Note "Count is too high" End If
MapBasic 10.5
43
User Guide
Chapter 4: MapBasic Fundamentals General Notes on MapBasic Syntax If your program references standard codes (such as CMD_INFO_DLG_OK in the example above), your program must issue an Include statement to include mapbasic.def. If you omit the Include statement, your program will generate a runtime error (for example, Variable or Field CMD_INFO_DLG_OK not defined).
Variables
MapBasics syntax for declaring and assigning values to variables is much like the syntax of other modern BASIC languages. However, MapBasic supports some types of variables that are not available in other languages (such as the Object variable; for a complete list of MapBasic variable types, see the description of the Dim statement in the MapBasic Reference Guide).
What Is a Variable?
Think of a variable as a very small piece of your computers memory. As you write programs, you will find that you need to temporarily store various types of information in memory. To do this, you declare one or more variables. Each variable has a unique name (for example, counter, x, y2, customer_name). For each variable that you declare, MapBasic sets aside a small piece of memory. Thereafter, each variable can contain one small piece of information.
Chapter 4: MapBasic Fundamentals General Notes on MapBasic Syntax The following example declares an Integer variable and assigns a value of 23 to that variable: Dim counter As Integer counter = 23 A single Dim statement can declare multiple variables, provided that the variable names are separated by commas. The following Dim statement declares three floating-point numeric variables: Dim total_distance, longitude, latitude As Float longitude = -73.55 latitude = 42.917 A single Dim statement can declare variables of different types. The following statement declares two Date variables and two String variables: Dim start_date, end_date As Date, first_name, last_name As String
Variable Names
Variable names must conform to the following rules: Each variable name can be up to thirty-one characters long. Variable names may not contain spaces. Each variable name must begin with a letter, an underscore (_) or a tilde (~). Each variable name can consist of letters, numbers, pound signs (#), or underscore characters (_). A variable name may end in one of the following characters: $, %, &, !, or @. In some BASIC languages, these characters dictate variable types. In MapBasic, however, these characters have no special significance. You may not use a MapBasic keyword as a variable name. Thus, you may not declare variables with names such as If, Then, Select, Open, Close, or Count. For a list of reserved keywords, see the discussion of the Dim statement in the MapBasic Reference Guide.
Data Types
MapBasic supports the following types of variables: Type SmallInt Integer Float String String * n Logical Date
MapBasic 10.5
Description Integer value between -32767 and 32767; stored in two bytes. Integer value between -2 billion and 2 billion; stored in four bytes. Floating-point value; stored in eight-byte IEEE format. Variable-length character string, up to 32,767 characters long. Fixed-length character string, n characters long (up to 32,767 characters). True or False. Date.
45 User Guide
Chapter 4: MapBasic Fundamentals General Notes on MapBasic Syntax Type Object Alias Pen Brush Description Graphical object, such as a line or a circle; see Graphical Objects for details. Column reference of a table; see Working With Tables for details. Pen (line) style setting; see Graphical Objects. Brush (fill) style setting; see Graphical Objects.
Array Variables
To declare an array variable, follow the variable name with the size of the array enclosed in parentheses. The array size must be a positive integer constant expression. The following Dim statement declares an array of ten Date variables: Dim start_date(10) As Date To refer to an individual element of an array, use the syntax: array_name(element-number) Thus, the following statement assigns a value to the first element of the start_date array: start_date(1) = "6/11/93" To resize an array, use the ReDim statement. Thus, in cases where you do not know in advance how much data your program will need to manageperhaps because you do not know how much data the user will enteryour program can use the ReDim statement to enlarge the array as needed. Use the UBound( ) function to determine the current size of an array.
MapBasic 10.5 46 User Guide
Chapter 4: MapBasic Fundamentals General Notes on MapBasic Syntax The following example declares an array of String variables called name_list. The latter part of the program increases the size of the array by ten elements. Dim counter As Integer, name_list(5) As String ... counter = UBound(names) Determine current array size ReDim names(counter + 10) Increase array size by 10 MapBasic arrays are subject to the following rules: MapBasic supports only one-dimensional arrays. In MapBasic, the first element in an array always has an index of one. In other words, in the example above, the first element of the names array is names(1).
If you need to store more data than will fit in an array, you may want to store your data in a table. For more information on using tables, see Working With Tables. MapBasic initializes the contents of numeric arrays and variables to zero when they are defined. The contents of string arrays and variables are initially set to the null string.
MapBasic 10.5
47
User Guide
Chapter 4: MapBasic Fundamentals General Notes on MapBasic Syntax TypeEnd Type statements must appear outside of any sub procedure definition. Sub procedures are discussed later in this chapter. Typically, TypeEnd Type statements appear at or near the very top of your program. A Type definition may include elements of any other type, including previously-defined custom data types. You can also declare global variables and arrays of custom data types.
Global Variables
Variables declared with the Dim statement are local variables. A local variable may only be used within the procedure where it is defined. MapBasic also lets you declare global variables, which may be referenced within any procedure, anywhere in the program. To declare a global variable, use the Global statement. The syntax for the Global statement is identical to the syntax for the Dim statement, except that the keyword Global appears instead of the keyword Dim. Thus, the following Global statement declares a pair of global Integer variables: Global first_row, last_row As Integer Global statements must appear outside of any sub procedure definition. Sub procedures are discussed later in this chapter. Typically, Global statements appear at or near the top of the program. The following program declares several global variables, then references those global variables within a sub procedure. Declare Sub Main Declare Sub initialize_globals Global gx, gy As Float Declare global Float variables Global start_date As Date Declare global Date variable Sub Main Dim x, y, z As Float Declare Main procs local vars Call initialize_globals ... End Sub Sub initialize_globals gx = -1 Assign global var: GX gy = -1 Assign global var: GY start_date = CurDate() Assign global var: START_DATE End Sub Whenever possible, you should try to use local variables instead of global variables, because each global variable occupies memory for the entire time that your program is running. A local variable, however, only occupies memory while MapBasic is executing the sub procedure where the local variable is defined. MapBasic global variables can be used to exchange data with other software packages. When an application runs on Windows, other applications can use Dynamic Data Exchange to read and modify the values of MapBasic global variables.
MapBasic 10.5
48
User Guide
Scope of Variables
A sub procedure may declare a local variable which has the same name as a global variable. Thus, even if a program has a global variable called counter, a sub procedure in that program may also have a local variable called counter: Declare Sub Main Declare Sub setup Global counter As Integer ... Sub setup Dim counter As Integer counter = 0 ... End Sub If a local variable has the same name as a global variable, then the sub procedure will not be able to read or modify the global variable. Within the sub procedure, any references to the variable will affect only the local variable. Thus, in the example above, the statement: counter = 0 has no effect on the global counter variable. Upon encountering a reference to a variable name, MapBasic attempts to interpret the reference as the name of a local variable. If there is no local variable by that name, MapBasic attempts to interpret the reference as the name of a global variable. If there is no global variable by that name, MapBasic tries to interpret the reference as a reference to an open table. Finally, if, at runtime, the reference cannot be interpreted as a table reference, MapBasic generates an error message.
Expressions
In this section, we take a closer look at expressions. An expression is a grouping of one or more variables, constant values, function calls, table references, and operators.
What is a Constant?
An expression can be very simple. For example, the statement: counter = 23 assigns a simple integer expression namely, the value 23 to the variable, counter. We refer to the expression 23 as a numeric constant. You might think of a constant as a specific value you can assign to a variable. The following program declares a String variable, then assigns a string constant (the name Fred Mertz) to the variable: Dim name As String name = "Fred Mertz" The syntax for numeric expressions is different than the syntax for string expressions: string constants must be enclosed in double-quotation marks (for example, Fred Mertz) whereas numeric constants (for example, 23) are not. You cannot assign a String expression, such as Fred Mertz, to a numeric variable. For more information on constant expressions, see A Closer Look At Constants on page 51.
MapBasic 10.5
49
User Guide
What is an Operator?
An operator is a special character (for example, +, *, >) or a word (for example, And, Or, Not) which acts upon one or more constants, variables, or other values. An expression can consist of two or more values that are combined through an operator. In the following example, the plus operator (+) is used within the expression y + z, to perform addition. The result of the addition (the sum) is then assigned to the variable, x: Dim y = z = x = x, y, z As Float 1.5 2.7 y + z
In this example, the plus sign (+) acts as an operator specifically, a numeric operator. Other numeric operators include the minus operator (-), which performs subtraction; the asterisk (*), which performs multiplication; and the caret (^), which performs exponentiation. A complete list of numeric operators appears later in this chapter. The plus operator can also be used within a String expression to concatenate separate strings into one string. The following program builds a three-part string expression and stores the string in the variable, full_name: Dim first_name, last_name, middle_init, full_name As String first_name = "Fred " middle_init = "R. " last_name = "Mertz" full_name = first_name + middle_init + last_name At this point, the variable full_name contains: Fred R. Mertz
MapBasic 10.5
50
User Guide
Chapter 4: MapBasic Fundamentals Expressions a Dim statement declares a variable, x; and then an assignment statement assigns a value to the variable. The assignment statement incorporates a function call (calling the Sqr( ) function to calculate the square root of a number): Dim x As Float x = Sqr(2) Similarly, the following program uses the CurDate( ) function, which returns a Date value representing the current date: Dim today, yesterday As Date today = CurDate( ) yesterday = today - 1 The CurDate( ) function takes no parameters. When you call a function in MapBasic, you must follow the function name with a pair of parentheses, as in the example above, even if the function takes no parameters. MapBasic supports many standard BASIC functions, such as Chr$( ) and Sqr( ), as well as a variety of special geographic functions such as Area( ) and Perimeter( ).
Numeric Constants
Different types of numeric variables require different types of constants. For instance, the constant value 36 is a generic numeric constant. You can assign the value 36 to any numeric variable, regardless of whether the variable is Integer, SmallInt, or Float. The value 86.4 is a floating-point numeric constant.
String Constants
A String constant is enclosed in double quotation marks. For example:
MapBasic 10.5 51 User Guide
Chapter 4: MapBasic Fundamentals Expressions last_name = "Nichols" Each string constant can be up to 256 characters long. The double quotation marks are not actually part of the string constant, they merely indicate the starting and ending points of the string constant. If you need to incorporate a double-quotation mark character within a string constant, insert two consecutive double-quotation marks into the string. The following program illustrates how to embed quotation marks within a string: Note "The table ""World"" is already open."
Logical Constants
Logical constants can be either one (1) for TRUE or zero (0) for FALSE. Many MapBasic programs refer to the values TRUE and FALSE; note that TRUE and FALSE are actually defined within the standard MapBasic definitions file, mapbasic.def. To refer to standard definitions like TRUE and FALSE, a program must issue an Include statement, to include mapbasic.def. For example: Include "mapbasic.def" Dim edits_pending As Logical edits_pending = FALSE
Date Constants
To specify a date constant, enter an eight-digit Integer with the format YYYYMMDD. This example specifies the date December 31, 1995: Dim d_enddate As Date d_enddate = 19951231 Alternately, you can specify a string expression that acts as a date constant: d_enddate = "12/31/1995" When you specify a string as a date constant, the year component can be four digits or two digits: d_enddate = "12/31/95" You can omit the year, in which case the current year is used: d_enddate = "12/31" CAUTION: Using a string as a date constant is sometimes unreliable, because the results you get depend on how the users computer is configured. If the users computer is configured to use Month/Day/Year formatting, then 06/11/95 represents June 11, but if the computer is set up to use Day/Month/Year formatting, then 06/11/95 represents the 6th of November.
If the users computer is set up to use - as the separator, MapInfo Professional cannot convert string expressions such as 12/31 into dates. To guarantee predictable results, use the NumberToDate( ) function, which accepts the eight-digit numeric date syntax. (Numeric date constants, such as 19951231, are not affected by how the users computer is configured.) If you need to use strings as date valuesperhaps because you are reading date values from a text fileuse the Set Format statement to control how the strings are interpreted. For Set Format statement details, see the MapBasic Reference Guide or online Help.
MapBasic 10.5
52
User Guide
Chapter 4: MapBasic Fundamentals Expressions To configure date formatting options under Microsoft Windows, use the Regional Settings control panel.
Alias Constants
Alias variables are discussed in detail in Working With Tables. You can assign a string expression to a variable of type Alias. For example: Dim column_name As Alias column_name = "City" The following table contains examples of various types of constants. Types Integer SmallInt Float i = 1234567 m = 90 f = 4 size = 3.31 debt = 3.4e9 s_mesg = "Fred Mertz" Enclose string in double quotes. To embed quotes in a string, type two quotation marks. To include special characters use the Chr$( ) function. 1= true, 0 = false The MapBasic definition file defines TRUE and FALSE. Sample assignments Notes
String
Logical
Date
d_starting = 19940105 date_done = "3/23/88" paiddate = "12-24-1993" yesterday = CurDate( ) - 1 col_name = "Pop_1990" col_name = "COL1" Aliases can be assigned like strings. See Working With Tables for more information about Alias variables. There is no constant syntax for Pen expressions. There is no Brush constant syntax.
Alias
Pen
Brush
MapBasic 10.5
53
User Guide
Chapter 4: MapBasic Fundamentals Expressions Types Font Sample assignments lbl_font = MakeFont("Helv", 1, 20, BLACK, WHITE) loc_sym = MakeSymbol(44, RED, 16) Notes There is no Font constant syntax. There is no Symbol constant syntax. There is no Object constant syntax.
Symbol
Object
Numeric Operators
Each of the operators in the following table is a numeric operator. Two numeric values can be combined using a numeric operator to produce a numeric result. Operator + * / \ Mod ^ Performs addition subtraction multiplication division integer division integer remainder exponentiation x = a + b x = a - b x = a * b x = a / b x = a \ b x = a Mod b x = a ^ b Example
MapBasic 10.5
54
User Guide
10 / 8 10 \ 8 10 Mod 8
The minus sign (-) operator can be used to negate a numeric value x = -23
String Operators
The plus operator (+) lets you concatenate two or more string expressions into one long string expression. Note "Employee name: " + first_name + " " + last_name You can use the ampersand operator (&) instead of the plus operator when concatenating strings. The & operator forces both operands to be strings, and then concatenates the strings. This is different than the + operator, which can work with numbers or dates without forcing conversion to strings. The & character is also used to specify hexadecimal numbers (&Hnumber). When you use & for string concatenation, make sure you put a space before and after the & so that the MapBasic compiler does not mistake the & for a hex number prefix. The Like operator performs string comparisons involving wild-card matching. The following example tests whether the contents of a String variable begins with the string North: If s_state_name Like "North%" Then ... The Like operator is similar to the Like( ) function. For a description of the Like( ) function, see the MapBasic Reference Guide or online Help.
Date Operators
The plus and minus operators may both be used in date expressions, as summarized below. Expression date + integer date - integer date - date Returns a Date value, representing a later date a Date value, representing an earlier date an Integer value, representing the number of elapsed days
The following example uses the CurDate( ) function to determine the current date, and then calculates other date expressions representing tomorrows date and the date one week ago:
MapBasic 10.5
55
User Guide
Chapter 4: MapBasic Fundamentals Expressions Dim today, one_week_ago, tomorrow As Date, days_elapsed As Integer today = CurDate( ) tomorrow = today + 1 one_week_ago = today - 7 calculate days elapsed since January 1: days_elapsed = today - StringToDate("1/1")
Comparison Operators
A comparison operator compares two items of the same general type to produce a logical value of TRUE or FALSE. Comparison operators are often used in conditional expressions (for example, in an IfThen statement). Operator = <> < > <= >= BetweenAndvalue Returns TRUE if equal to not equal to less than greater than less than or equal to greater than or equal to is within range Example If a = b Then ... If a <> b Then ... If a < b Then ... If a > b Then ... If a <= b Then ... If a >= b Then ... If x Between f_low And f_high Then...
Each of these comparison operators may be used to compare string expressions, numeric expressions, or date expressions. Note, however, that comparison operators may not be used to compare Object, Pen, Brush, Symbol, or Font expressions. The BetweenAnd comparison operator lets you test whether a data value is within a range. The following IfThen statement uses a BetweenAnd comparison: If x Between 0 And 100 Then Note "Data within range." Else Note "Data out of range." End If The same program could be written another way: If x >= 0 And x <= 100 Then Note "Data within range." Else Note "Data out of range." End If
MapBasic 10.5
56
User Guide
Chapter 4: MapBasic Fundamentals Expressions When you use the = operator to compare two strings, MapBasic examines the entire length of both strings, and returns TRUE if the strings are identical. String comparisons are not case sensitive; so this IfThen statement considers the two names (Albany and ALBANY) to be identical: Dim city_name As String city_name = "ALBANY" If city_name = "Albany" Then Note "City names match." End If If you wish to perform case-sensitive string comparison, use the StringCompare( ) function, which is described in the MapBasic Reference Guide. Be careful when comparing fixed-length and variable-length strings. MapBasic automatically pads every fixed-length string with spaces, if necessary, to ensure that the string fills the allotted space. Variable-length strings, however, are not padded in this manner. Depending on your data and variables, this difference might mean that two seemingly-identical strings are not actually equal. You can use the RTrim$( ) function to obtain a non-padded version of a fixed-length string. You then can compare the value returned by RTrim$( ) with a variable-length string, without worrying about interference from padded spaces.
Logical Operators
Logical operators operate on logical values to produce a logical result of TRUE or FALSE: Operator And Or Not Returns TRUE if both operands are TRUE either operand is TRUE operand is FALSE. Example If a And b Then If a Or b Then If Not a Then
For example, the following IfThen statement performs two tests, testing whether the variable x is less than zero, and testing whether x is greater than ten. The program then displays an error message if either test failed. If x < 0 Or x > 10 Then Note "Number is out of range." End If
MapBasic 10.5
57
User Guide
Geographic Operators
These operators act on Object expressions to produce a logical result of TRUE or FALSE. Operator Contains Returns TRUE if first object contains centroid of second object first object contains part of second object first object contains all of second object first objects centroid is within second object part of first object is within second object all of first object is within second object the two objects intersect at some point Example If a Contains b Then...
Contains Part
Contains Entire
Within
If a Within b Then...
Partly Within
Entirely Within
Intersects
If a Intersects b Then...
Chapter 4: MapBasic Fundamentals Looping, Branching, and Other Flow-Control The following table identifies the precedence of each MapBasic operator. Highest priority: parentheses exponentiation negation multiplication, division, Mod, integer division addition, subtraction, string concatenation (&) geographic operators, comparison operators, Like Not And Lowest Priority: Or
Operators appearing on the same row have equal precedence. Operators of higher priority are processed first. Operators of the same precedence are evaluated left to right in the expression, except exponentiation, which evaluates from right to left.
IfThen Statement
MapBasics IfThen statement is very similar to comparable IfThen statements in other languages. The IfThen statement tests a condition; if the condition is TRUE, MapBasic executes the statements which follow the Then keyword. In the following example, MapBasic displays an error message and calls a sub-procedure if a counter variable is too low: If counter < 0 Then Note "Error: The counter is too low." Call reset_counter End If An IfThen statement can have an optional Else clause. In the event that the original test condition was FALSE, MapBasic executes the statements following the Else keyword instead of executing the statements following the Then keyword.
MapBasic 10.5
59
User Guide
Chapter 4: MapBasic Fundamentals Looping, Branching, and Other Flow-Control The following example demonstrates the optional Else clause. If counter < 0 Then Note "Error: The counter is too low." Call reset_counter Else Note "The counter is OK." End If An IfThen statement can also have one or more optional ElseIf clauses. The ElseIf clause tests an additional condition. If the statement includes an ElseIf clause, and if the original condition turned out to be FALSE, MapBasic will test the ElseIf clause, as in the following example: If counter < 0 Then Note "Error: The counter is too low." Call reset_counter ElseIf counter > 100 Then counter = 100 Note "Error: The counter is too high; resetting to 100." Else Note "The counter is OK." End If ElseIf is a single keyword. A single IfThen statement can include a succession of two or more ElseIf clauses, subsequently testing for condition after condition. However, if you want to test for more than two or three different conditions, you may want to use the DoCase statement (described below) instead of constructing an IfThen statement with a large number of ElseIf clauses.
Do Case Statement
The Do Case statement performs a series of conditional tests, testing whether a certain expression is equal to one of the values in a list of potential values. Depending on which value the expression matches (if any), MapBasic carries out a different set of instructions. The following example tests whether the current month is part of the first, second, third, or fourth quarter of the fiscal year. If the current month is part of the first quarter (January-February-March), the program assigns a text string an appropriate title (First Quarter Results). Alternately, if the current month is part of the second quarter, the program assigns a different title (Second Quarter Results), etc. Dim current_month, quarter As SmallInt, report_title As String current_month = Month( CurDate() ) At this point, current_month is 1 if current date is in January, 2 if current date is in February, etc. Do Case current_month Case 1, 2, 3 If current month is 1 (Jan), 2 (Feb) or 3 (Mar), were in the First fiscal quarter. Assign an appropriate title.
MapBasic 10.5 60 User Guide
Chapter 4: MapBasic Fundamentals Looping, Branching, and Other Flow-Control report_title = "First Quarter Results" quarter = 1 Case 4, 5, 6 report_title = "Second Quarter Results" quarter = 2 Case 7, 8, 9 report_title = "Third Quarter Results" quarter = 3 Case Else If current month wasnt between 1 and 9, then current date must be in the Fourth Quarter. report_title = "Fourth Quarter Results" quarter = 4 End Case Case Else is an optional clause of the Do Case statement. If a Do Case statement includes a Case Else clause, and if none of the previous Case clauses matched the expression being tested, MapBasic carries out the statements following the Case Else clause. The Case Else clause must be the final clause in the Do Case construction.
GoTo Statement
The GoTo statement tells MapBasic to go to a different part of the program and resume program execution from that point. The GoTo statement specifies a label. For the GoTo statement to work, there must be a label elsewhere within the same procedure. A label is a name which begins a line. Each label must end with a colon (although the colon is not included in the GoTo statement). See the example below. If counter < 0 Then GoTo get_out End If ... get_out: End Program Many programming professionals discourage the use of GoTo statements. Careful use of other flowcontrol statements, such as IfThen, usually eliminates the need to use GoTo statements. Thus, if you like, you may avoid using GoTo statements.
ForNext Statement
The ForNext statement sets up a loop that executes a specific number of times. With each iteration of the loop, MapBasic executes all statements that appear between the For and Next clauses. When creating a ForNext loop, you must specify the name of a numeric variable as a counter. You must also specify that counter variables starting and ending values. With each iteration of the loop, MapBasic increments the counter variable by some step value. By default, this step value is one. To use a different increment, include the optional Step clause.
MapBasic 10.5 61 User Guide
Chapter 4: MapBasic Fundamentals Looping, Branching, and Other Flow-Control The following example uses a ForNext loop to add the values from an array of numbers: Dim monthly_sales(12), grand_total As Float, next_one As SmallInt ... For next_one = 1 To 12 grand_total = grand_total + monthly_sales(next_one) Next At the start of the ForNext statement, MapBasic assigns the start value to the counter variable. In the example above, MapBasic assigns a value of one to the variable: next_one. MapBasic then executes the statements that appear up to the Next keyword. After each iteration of the loop, MapBasic increments the counter variable. If the counter variable is less than or equal to the end value (for example, if next_one is less than or equal to twelve), MapBasic performs another iteration of the loop. A ForNext loop halts immediately if it encounters an Exit For statement. This allows you to conditionally halt the loop prematurely. See the MapBasic Reference Guide for more information on the ForNext loop.
DoLoop
The DoLoop statement continually executes a group of statements for as long as a test condition remains TRUE or, optionally, for as long as the condition remains FALSE. There are different forms of the DoLoop statement, depending on whether you want to test the looping condition before or after the body of the statements that are executed. The following program tests the loop condition at the end of the loop: Dim sales_total, new_accounts(10) As Float, next_one As SmallInt next_one = 1 Do sales_total = sales_total + new_accounts(next_one) next_one = next_one + 1 Loop While next_one <= UBound(new_accounts) Note that the preceding loop always executes for at least one iteration, because the looping condition is not tested until the end of the loop. The following loop tests the loop condition at the start of the loop. Because the condition is tested at the start of the loop, the statements within the body of the loop may never be executed. If the test condition is FALSE from the beginning, the statements within the following DoLoop will never be executed. Dim sales_total, new_accounts(10) As Float, next_one As SmallInt next_one = 1 Do While next_one <= UBound(new_accounts) sales_total = sales_total + new_accounts(next_one) next_one = next_one + 1 Loop
MapBasic 10.5 62 User Guide
Chapter 4: MapBasic Fundamentals Looping, Branching, and Other Flow-Control In the examples above, both DoLoop statements included the keyword While; thus, both loops continue while the test condition remains TRUE. Alternately, a DoLoop can use the Until keyword instead of the keyword While. If a DoLoop statement specifies Until, the loop will continue only for as long as the test condition remains FALSE. A DoLoop statement halts immediately if it encounters an Exit Do statement. This statement allows you to conditionally terminate a loop prematurely.
WhileWend Loop
MapBasic supports the conventional BASIC WhileWend loop syntax. A WhileWend statement is very similar to a Do WhileLoop statement. If you are an experienced BASIC programmer, and you therefore are in the habit of using WhileWend statements, you can continue to use WhileWend statements as you use MapBasic. Note, however, that the DoLoop statement syntax is in some ways more powerful than the WhileWend syntax. You can exit a DoLoop statement prematurely, through the Exit Do statement, but there is no corresponding statement for exiting a WhileWend loop. See the MapBasic Reference Guide for more information on the WhileWend loop.
MapBasic 10.5
63
User Guide
Procedures
Procedures (often referred to as sub-procedures) are an integral part of the MapBasic program architecture. A typical MapBasic program is comprised of numerous sub-procedures; each subprocedure contains a group of statements that perform a specific task. By breaking your program into several sub-procedures, you modularize your program, making program development and maintenance easier in the long run.
Main Procedure
Every MapBasic program has at least one procedure, known as the Main procedure. When you run a MapBasic application, MapBasic automatically calls that applications Main procedure. The following program demonstrates the syntax for explicitly declaring the Main procedure. In this example, the Main procedure simply issues a Note statement: Declare Sub Main Sub Main Note "Hello from MapBasic!" End Sub The Declare Sub statement tells MapBasic that a sub-procedure definition will occur further down. You must have one Declare Sub statement for each sub-procedure in your program. The Declare Sub statement must appear before the actual sub-procedure definition. Typically, Declare Sub statements appear at or near the top of your program. You may recall from Using the Development Environment that a MapBasic program can be as simple as a single line. For example, the following statement: Note "Hello from MapBasic!" is a complete MapBasic program which you can compile and run. Note that even a simple, one-line program has a Main procedure. However, in this case, we say that the Main procedure is implied rather than being explicit.
Calling a Procedure
When you run a compiled application, MapInfo Professional automatically calls the Main procedure (regardless of whether the Main procedure is implied or explicitly defined). The Main procedure can then call other sub-procedures through the Call statement. The following program contains two procedures: a Main procedure, and a procedure called announce_date. Declare Sub Main Declare Sub announce_date Sub Main Call announce_date( ) End Sub Sub announce_date
MapBasic 10.5 64 User Guide
Chapter 4: MapBasic Fundamentals Procedures Note "Todays date is " + Str$( CurDate() ) End Sub
Thus, in the example above, the Call statement specifies the name of a Date variable report_date: Call check_date( report_date ) Then, within the check_date procedure, the parameter is known by the name last_date. When the check_date procedure performs the assignment last_date = CurDate( ), MapBasic automatically updates the Main procedures report_date variable.
MapBasic 10.5
65
User Guide
The following example shows a procedure (display_date_range) which takes two by-value Date parameters. Declare Sub Main Declare Sub display_date_range(ByVal start_date As Date, ByVal end_date As Date ) Sub Main Call display_date_range( "1/1", CurDate() ) End Sub Sub display_date_range(ByVal start_date As Date, ByVal end_date As Date ) Note "The report date range will be: " + Str$(start_date) + " through " + Str$(end_date) + "." End Sub In this example, both of the parameters to the display_date_range procedure are by-value date parameters. Thus, when the Main procedure calls display_date_range: Call display_date_range( "1/1", CurDate() ) neither of the parameters needs to be a Date variable. The first parameter (1/1) is a constant Date expression, and the second parameter is a date expression derived by calling the CurDate( ) function.
MapBasic 10.5
67
User Guide
Nature of Handler Procedure or Function Called when the application terminates or when the user exits MapInfo Professional. EndHandler can be used to do clean-up work (for example, deleting temporary work files). Called when MapInfo Professional gets the focus (becomes the active application) or loses the focus. Called when an OLE Automation client calls the MapGenHandler method; used primarily in MapInfo ProServer applications. Called when the application is acting as the server in an interprocess conversation, and the remote client sends an execute request. Called when the application is acting as the server in an interprocess conversation, and the remote client sends a peek request. Called whenever the Selection table changes. Since the Selection table changes frequently, the SelChangedHandler procedure should be as brief as possible to avoid slowing system performance. Called when the user clicks in a Mapper, Browser, or Layout window using the MapBasic tool. Called when the user pans, scrolls, or otherwise resets the area displayed in a Mapper. Since Mapper windows can change frequently, the WinChangedHandler procedure should be as brief as possible to avoid slowing system performance. Called when the user closes a Mapper, Browser, Grapher, or Layout. Called when the window focus changes (i.e., when the user changes which window is the active window).
ForegroundTaskSwitchHandler
RemoteMapGenHandler
RemoteMsgHandler
RemoteQueryHandler( )
SelChangedHandler
ToolHandler
WinChangedHandler
WinClosedHandler
WinFocusChangedHandler
Typically, you do not use the Call statement to call the special procedures listed above. If your program contains one of these specially named procedures, MapBasic calls that procedure automatically, when and if a certain type of system event occurs. For example, if your program contains a procedure called WinClosedHandler, MapBasic automatically calls the WinClosedHandler procedure every time the user closes a window.
MapBasic 10.5
68
User Guide
Chapter 4: MapBasic Fundamentals Procedures That Act As System Event Handlers All of the special handler procedures are optional. Thus, you should only include a WinClosedHandler procedure in your application if you want your application to be notified every time a window is closed. You should only include a SelChangedHandler procedure in your application if you want your application to be notified each time Selection changes, etc. The following program defines a special event-handler procedure named ToolHandler. Note that this program does not contain any Call statements. Once this program is running, MapBasic calls the ToolHandler procedure automatically, when and if the user selects the MapBasic tool and clicks on a Mapper, Browser, or Layout window. Include "mapbasic.def" Declare Sub Main Declare Sub ToolHandler Sub Main Note "The ToolHandler demonstration is now in place. " + "Select the MapBasic tool (+) and click on a Map " + "to see a printout of map coordinates." End Sub Sub ToolHandler If WindowInfo( FrontWindow(), WIN_INFO_TYPE ) = WIN_MAPPER Then Print "X: " + Str$( CommandInfo(CMD_INFO_X) ) Print "Y: " + Str$( CommandInfo(CMD_INFO_Y) ) Print " " End If End Sub Within a system event handler procedure, you can call the CommandInfo( ) function to learn more about the event that made MapBasic call the handler. In the example above, the ToolHandler procedure calls CommandInfo( ) to determine the map coordinates where the user clicked. The following sample SelChangedHandler procedure appears in the sample program, TextBox (textbox.mb). This procedure automatically disables (grays out) a menu item whenever the user deselects all rows, and automatically re-enables the menu item whenever the user selects more rows. See textbox.mb for more details. Sub SelChangedHandler If SelectionInfo(SEL_INFO_NROWS) < 1 Then Alter Menu Item create_sub Disable Else Alter Menu Item create_sub Enable End If End Sub
Chapter 4: MapBasic Fundamentals Tips for Handler Procedures application remains dormant in memory until an appropriate event occurs (for example, until the user clicks with the MapBasic tool). When the event occurs, MapBasic automatically calls the sleeping applications handler procedure. If any procedure in an application issues the End Program statement, the entire application is removed from memory, regardless of whether the application contains special handler procedures. You must avoid using the End Program statement for as long as you want your program to remain available. Custom MapBasic menus work in a similar manner. If a MapBasic application adds its own items to the MapInfo Professional menu structure, the application goes to sleep and waits for the user to choose one of the custom menu items. For a complete discussion of how to customize MapInfo Professionals menus, see Creating the User Interface.
Issuing a Select statement here will not cause an infinite loop. Set Handler SelChangedHandler On End Sub
Custom Functions
The MapBasic language supports many different functions. Some are standard BASIC functions (for example, Asc( ), Format$( ), Val( ), etc.) and some are unique to MapInfo Professional and MapBasic (for example, Distance( ) and ObjectGeography( ) ). MapBasic also lets you define custom functions. Once you have defined a custom function, you can call that function just as you can call any of MapBasics standard functions. The body of a custom function is defined within a FunctionEnd Function construction, which is syntactically very similar to a SubEnd Sub construction. The general syntax of a FunctionEnd Function construct is as follows: Function function_name( parameters, if any ) As data_type statement list End Function The function itself has a data type. This dictates which type of value (for example, Integer, Date, String) the function returns when called. Within the body of the FunctionEnd Function construction, the function name acts like a byreference parameter. A statement within the FunctionEnd Function construction can assign a value to the function name; this is the value that MapBasic later returns to the functions caller. The example below defines a custom function called money_format( ). The money_format( ) function takes one numeric parameter (presumably representing a sum of money), and returns a string (obtained by calling the Format$( ) function) representing the dollar amount, formatted with commas. Declare Sub Main Declare Function money_format(ByVal num As Float) As String Sub Main Dim dollar_amount As String dollar_amount = money_format( 1234567.89 ) dollar_amount now contains the string: "$1,234,567.89" End Sub Function money_format(ByVal num As Float) As String money_format = Format$(num, "$,#.##;($,#.##)") End Function
Scope of Functions
A program can define a custom function that has the same name as a standard MapBasic function. When the program calls the function, the custom function is executed instead of the standard function.
MapBasic 10.5
71
User Guide
Compiler Instructions
MapBasic provides two special statements which make it easier to manage large-scale application development: The Define statement lets you define a shorthand identifier which has a definition; the definition is substituted for the identifier at compile time. The Include statement lets you combine two or more separate program files into one compilable program.
Chapter 4: MapBasic Fundamentals Program Organization Many MapBasic applications use the Include statement to include the standard MapBasic definitions file, mapbasic.def: Include "mapbasic.def" mapbasic.def provides Define statements for many standard MapBasic identifiers (TRUE, FALSE, RED, GREEN, BLUE, TAB_INFO_NAME, etc.). The filename that you specify can include a directory path. If the filename that you specify does not include a directory path, the MapBasic compiler looks for the file in the current working directory. If the file is not found in that directory, the compiler looks in the directory where the MapBasic software is installed. As you develop more and more MapBasic programs, you may find that you use certain sections of code repeatedly. Perhaps you have written a library of one or more custom functions, and you wish to use those custom functions in every MapBasic program that you write. You could put your custom functions into a separate text file, perhaps calling the text file functs.mb. You could then incorporate the function library into another program by issuing the statement: Include "functs.mb" Using Include statements also lets you work around the memory limitations of the MapBasic text editor. As discussed in Using the Development Environment, each MapBasic edit window is subject to memory limits; once a program file grows too large, you can no longer add statements to the file using a MapBasic edit window. If this happens, you may want to break your program into two or more separate program files, then combine the files using the Include statement. Alternately, you could combine the separate modules using a project file; see Using the Development Environment for details.
Program Organization
A MapBasic application can include any or all of the different types of statements described in this chapter. However, the different pieces of a MapBasic program must be arranged in a particular manner. For example, Global statements may not be placed inside of a SubEnd Sub definition. The following illustration shows a typical arrangement of the various program components. Global level statements appear at the top of the program Include "mapbasic.def" other Include statements Type...End Type statements Declare Sub statements Declare Function statements Define statements Global statements followed by the Main procedure definition Sub Main Dim statements ... End Sub
MapBasic 10.5 73 User Guide
Chapter 4: MapBasic Fundamentals Program Organization followed by additional sub-procedure definitions Sub ... Dim statements ... End Sub and custom Function definitions Function ... Dim statements ... End Function
MapBasic 10.5
74
User Guide
Even if your program compiles successfully, it may still contain runtime errors (errors that occur when you run your program). For example, if your program creates large database files, the program may generate an error condition if you run it when there is no free disk space. This chapter shows you how to deal with runtime errors. This is a two-step process: first, you debug your program to find out where the error occurs; then, you modify your program to prevent the error from happening again.
The error message identifies the name of the program file and the line number at which the error occurred. In the example above, the name of the program is map_it, and the line number containing the error is 16. This line number identifies which part of your program caused the runtime error. Once you know the line number, you can return to the MapBasic development environment and use the Go To Line command (on the Search menu) to locate the statement that caused the problem.
MapBasic 10.5
76
User Guide
Chapter 5: Debugging and Trapping Runtime Errors Debugging a MapBasic Program 2. Recompile and run your program. When your program reaches the Stop statement, MapBasic temporarily suspends execution of your program and displays a debugging message in the MapBasic window (for example, Breakpoint at textbox.mb line 23"). 3. Within the MapBasic window: Type ? Dim to see a list of all local variables that are in use. Type ? Global to see a list of all global variables that are in use. Type ? variable_name to see the current contents of a variable. Type ? variable_name = new_value to change the contents of that variable. 4. When you are finished examining and modifying the contents of variables, type Continue in the MapBasic window to resume program execution. Alternately, you can choose the Continue Program command from MapInfo Professionals File menu. Note that while a program is suspended, the File menu contains a Continue Program command instead of a Run Program command.
MapBasic 10.5
77
User Guide
Chapter 5: Debugging and Trapping Runtime Errors Error Trapping Through the Run Application statement, one MapBasic application can spawn another application. However, you may not use the Stop statement to suspend execution of the spawned application. Even without using the Run Application statement, it is possible to run separate MapBasic programs at one time. For example, if you run the TextBox application, TextBox creates its own custom menu, then remains sleeping until you choose an item from that menu. After loading TextBox, you can run other MapBasic applications. However, you may not use the Stop statement while you have multiple applications running simultaneously.
Error Trapping
A well-designed program anticipates the possibility of runtime errors and includes precautions whenever possible. Intercepting and dealing with runtime errors is known as error trapping. In MapBasic, error trapping involves using the OnError statement. Veteran BASIC programmers take note: in MapBasic, OnError is a single keyword. At any point during execution, error trapping is either enabled or disabled. By default, all procedures and functions start with error trapping disabled. The OnError statement enables error trapping. Typically, OnError specifies a label that must appear at another location in the same procedure or function. The statements following the label are known as the error-trapping routine. If an error occurs while an error-trapping routine has been enabled, MapBasic jumps to the specified label and executes the error-trapping routine instead of halting the application. Within the error-trapping routine, you can call the Err( ) function to obtain an Integer code indicating which error occurred. Similarly, Error$( ) returns a string describing the error message. For a complete listing of potential MapBasic error codes and their descriptions, see the text file errors.doc which is included with MapBasic. Each error-trapping routine ends with a Resume statement. The Resume statement tells MapBasic which line to go to once the error-trapping routine is finished. For more about error trapping, see OnError, Resume, Err( ) and Error$( ) in the MapBasic Reference Guide. MapBasic can only handle one error at a time. If you enable error-trapping and then an error occurs, MapBasic jumps to your error-handling routine. If another error occurs within the error-handling routine (i.e., before the Resume statement), your MapBasic application halts.
MapBasic 10.5
78
User Guide
MapBasic 10.5
79
User Guide
The user interface is an important part of every application. MapBasic provides you with all the tools you need to customize MapInfo Professionals user interface.
Chapter 6: Creating the User Interface Introduction to MapBasic User Interface Principles
The sample application, OverView, demonstrates many aspects of a custom interface created in MapBasic. When the user runs OverView, MapBasic adds custom items to the Tools menu. If the user chooses the custom Setup Overview menu item, MapBasic displays a custom dialog box. If the user chooses a table from this dialog box, MapBasic opens a new Map window to display the table.
Event-Driven Programming
MapBasic follows a programming model known as event-driven programming. To understand how a MapBasic program can create a custom user interface, you must first understand the basic principles of event-driven programming.
What Is an Event?
In a Graphical User Interface environment, the user controls what happens by typing and by using the mouse. Technically, we say that mouse-clicks and other actions taken by the user generate events. There are many different kinds of events; for example, when the user chooses a menu item, we say that the user has generated a menu-choose event, and when the user closes a window, we say the user has generated a window-close event.
MapBasic 10.5
81
User Guide
Chapter 6: Creating the User Interface Event-Driven Programming If a MapBasic application creates a custom menu, and the user chooses an item from that menu, the MapBasic application handles the menu-choose event. Typically, the MapBasic application handles the event by calling a procedure. In this situation, we say that the procedure acts as an eventhandler, or handler for short. Thus, creating custom menu items is typically a two-step process: 1. Customize the MapInfo Professional menu structure, using statements such as Create Menu or Alter Menu. 2. Specify a handler for each custom menu item. A handler can be a sub-procedure that appears elsewhere in your program. Set up each handler procedure to perform whatever tasks are appropriate for the corresponding menu item(s). Alternately, instead of specifying a procedure as the menu items handler, you can specify that the menu item call a standard MapInfo Professional command. Thus, you could create a custom menu item that invokes the Create Thematic Map command (from MapInfo Professionals Map menu). As noted in Using the Development Environment, the Call statement lets you call a subprocedure. However, when a sub-procedure acts as an event-handler, you do not issue any Call statements. Instead of issuing Call statements, you include a Calling clause within the Create Menu statement. For example, the TextBox application issues the following Create Menu statement: Create Menu "TextBox" As "&Create Text Boxes..." Calling create_sub, "Close TextBox" Calling Bye, "About TextBox..." Calling About This statement creates a custom menu with several menu items, each of which contains a Calling clause (for example, Calling create_sub). Each Calling clause identifies the name of a procedure that appears elsewhere in the TextBox.mb program. Thus, create_sub, Bye, and About are all sub-procedure names. When and if the user chooses the Create Text Boxes item from the TextBox menu, MapBasic automatically calls the create_sub procedure. Thus, the create_sub procedure acts as the handler for that menu item.
MapBasic 10.5
82
User Guide
Menus
Menus are an essential element of the graphical user interface. Accordingly, the MapBasic language lets you control every aspect of MapInfo Professionals menu structure. With a few lines of code, you can customize any or all of MapInfo Professionals menus or menu items.
Menu Fundamentals
MapInfo Professionals menu structure consists of the following elements: The menu bar is the horizontal bar across the top of the MapInfo Professional work area. The default MapInfo Professional menu bar contains words such as File, Edit, Objects, Query, etc. A menu is a vertical list of commands that drops down if you click on the menu bar. For example, most applications include a File menu and an Edit menu. A menu item is an individual command that appears on a menu. For example, the File menu typically contains menu items such as Open, Close, Save, and Print. Menu items are sometimes referred to as commands (for example, the File > Save command. 1 2
1 Menu 2 Menu Bar 3 Menu Items The concepts of menu, menu bar, and menu item are interrelated. Each menu is a set of menu items. For example, the File menu contains items such as Open, Close, Save, etc. The menu bar is a set of menus.
MapBasic 10.5 83 User Guide
Chapter 6: Creating the User Interface Menus When the user chooses a menu item, some sort of action is initiated. Different menu items invoke different types of actions; some menu items cause dialog boxes to be displayed, while other menu items produce an immediate effect. The action associated with a menu item is referred to as the menu items handler. A menu item handler can either be a standard MapInfo Professional command code or a custom MapBasic subprocedure name. In other words, when the user chooses a menu item, MapInfo Professional handles the menu-choose event, either by running a standard command code or by calling a subprocedure from your application.
Chapter 6: Creating the User Interface Menus If you want to remove several items from a menu, there are two techniques you can use: you can issue an Alter MenuRemove statement which lists all the items you wish to remove; or you can issue a Create Menustatement which redefines the menu entirely, including only the items you want. For example, the following statement creates a simplified version of the Map menu that includes only three items (Layer Control, Previous View, and Options): Create Menu "Map" As "Layer Control" Calling M_MAP_LAYER_CONTROL, "Previous View" Calling M_MAP_PREVIOUS, "Options" Calling M_MAP_OPTIONS
In practice, adding menus onto the menu bar is sometimes problematic. The amount of space on the menu bar is limited, and every time you add a menu to the menu bar, you fill some of the remaining space. Therefore, for the sake of conserving space on the menu bar, the TextBox application uses a different technique for displaying its menu: instead of adding its menu directly onto the menu bar, the TextBox application uses an Alter Menu statement to add its menu as a hierarchical sub-menu, located on the Tools menu. Alter Menu "Tools" Add "(-", "TextBox" As "TextBox"
MapBasic 10.5
85
User Guide
Chapter 6: Creating the User Interface Menus As a result of this statement, the TextBox menu appears as a hierarchical menu located on the Tools menu. The resulting Tools menu looks like this:
Sample programs that are provided with MapInfo Professional, such as ScaleBar and OverView, follow the same convention (placing their menu items on hierarchical menus located off of the Tools menu). Thus, if you run the TextBox application, the ScaleBar application, and the OverView application, all three applications add their commands to the Tools menu. If each of the sample programs (ScaleBar, etc.) added a menu directly onto the menu bar, the menu bar would quickly become over-crowded. Stacking hierarchical menus onto the Tools menu (or any other menu) is one way of conserving space on the menu bar. Note, however, that some users find hierarchical menus significantly harder to use. How you design and organize your menus will depend on the nature of your application. Depending on your application, you may need to add one, two, or even several menus to the menu bar. Regardless of whether you attach your menus to the menu bar or to other menus, MapInfo Professional is limited to 96 menu definitions. In other words, there can never be more than 96 menus defined at one time, including MapInfo Professionals standard menus. This limitation applies even when you are not displaying all of the menus.
To alter a menu item, use the Alter Menu Item statement. The Alter Menu Item statement includes several optional clauses (Enable, Disable, Check, UnCheck, etc.); use whichever clauses apply to the change you want to make. The sample program OverView demonstrates the process of creating, then altering, a custom menu. The OverView application creates the following custom menu: Create Menu "OverView" As "&Setup OverView" Calling OverView,
MapBasic 10.5 86 User Guide
Chapter 6: Creating the User Interface Menus "(Suspend Tracking" Calling MenuToggler, "(Pick Frame Style" Calling PickFrame, "(-", "Close Overview" Calling Bye, "(-", "About Overview..." Calling About The Pick Frame Style menu item is initially disabled. (Whenever the name of a menu item begins with the ( character, that menu item is automatically disabled when the menu first appears.) When and if the user sets up an overview window, the OverView application enables the Pick Frame Style menu item, using the following statement: Alter Menu Item PickFrame Enable If the user closes the overview window, the application once again disables the Pick Frame menu item, by issuing the following statement: Alter Menu Item PickFrame Disable PickFrame is the name of a sub-procedure in overview.mb. Note that PickFrame appears in both the Create Menu statement (in the Calling clause) and in the Alter Menu Item statements. When you issue an Alter Menu Item statement, you must specify which menu item you want to alter. If you specify the name of a procedure (for example, PickFrame), MapInfo Professional modifies whatever menu item calls that procedure. Similarly, to enable the Suspend Tracking menu item, issue the following statement: Alter Menu Item MenuToggler Enable You also can use Alter Menu Item to change the name of a menu item. For example, the OverView application has a menu item that is initially called Suspend Tracking. If the user chooses Suspend Tracking, the application changes the menu items name to Resume Tracking by issuing the following statement: Alter Menu Item MenuToggler Text "Resume Tracking" Note that MapInfo Professional enables and disables its own standard menu items automatically, depending on the circumstances. For example, the Window > New Map Window command is only enabled when and if a mappable table is open. Because MapInfo Professional automatically alters its own standard menu items, a MapBasic application should not attempt to enable or disable those menu items.
Chapter 6: Creating the User Interface Menus Alter Menu Bar Add "Map", "Browse" The Alter Menu Bar Add statement always adds menus to the right end of the menu bar. One minor disadvantage of this behavior is the fact that menus can end up located to the right of the Help menu. Most software packages arrange the menu bar so that the last two menu names are Window and Help. Therefore, you may want to insert your custom menu to the left of the Window menu. The following statements show how to insert a menu to the left of the Window menu: Alter Menu Bar Remove ID 6, ID 7 Alter Menu Bar Add "Tools", ID 6, ID 7 The first statement removes the Window menu (ID 6) and Help menu (ID 7) from the menu bar. The second statement adds the Tools menu, the Window menu, and the Help menu to the menu bar. The end result is that the Tools menu is placed to the left of the Window menu. For complete control over the menu order, use the Create Menu Bar statement. For example, this statement re-defines the menu bar to include the File, Edit, Map, Query, and Help menus (in that order): Create Menu Bar As "File", "Edit", "Map", "Query", "Help" For a list of MapInfo Professionals standard menu names (File, Query etc.) see Alter Menu in the MapBasic Reference Guide or online Help. To restore MapInfo Professionals standard menu definitions, issue a Create Menu Bar As Default statement.
MapBasic 10.5
88
User Guide
Chapter 6: Creating the User Interface Menus Each shortcut menu has a unique name and ID number. For example, the shortcut menu that appears when you right-click a Map window is called MapperShortcut and has an ID of 17. For a listing of the names and ID numbers of the shortcut menus, see Alter Menu in the MapBasic Reference Guide or online Help. To destroy a shortcut menu, use the Create Menu statement to re-define the menu, and specify the control code (- as the new menu definition. For example: Create Menu "MapperShortcut" ID 17 As "(-"
MapBasic 10.5
89
User Guide
Chapter 6: Creating the User Interface Menus Menu item ID numbers can be any positive Integer.
MapBasic 10.5
90
User Guide
The menus file contains several Create Menu statements. These statements define MapInfo Professionals standard menu definitions (File, Edit, etc.). If you wish to remove one or more menu items from a menu, you can do so by removing appropriate lines from the appropriate Create Menu statement. For example, MapInfo Professionals Table > Maintenance menu usually contains a Delete Table command, as shown below.
If you examine the menus file, you will see that the Maintenance menu is defined through a Create Menu statement that looks like this: Create Menu "&Maintenance" As "&Table Structure..." HelpMsg "Modify the table structure." calling 404, "&Delete Table..." HelpMsg "Delete a table and its component files. " calling 409, "&Rename Table..." HelpMsg "Rename a table and its component files." calling 410, "&Pack Table..." HelpMsg "Compress tables to conserve space and eliminate deleted records." calling 403, . . .
MapBasic 10.5 91 User Guide
Chapter 6: Creating the User Interface Menus Because the Delete Table command is potentially dangerous, you might want to re-define the Maintenance menu to eliminate Delete Table. To eliminate the Delete Table command from the menu, remove the appropriate lines ("&Delete Table" through to calling 409) from the menus file. After you make this change, the Create Menu statement will look like this: Create Menu "&Maintenance" As "&Table Structure..." HelpMsg "Modify the table structure." calling 404, "&Rename Table..." HelpMsg "Rename a table and its component files." calling 410, "&Pack Table..." HelpMsg "Compress tables to conserve space and eliminate deleted records." calling 403, . . . The next time you run MapInfo Professional, the Table > Maintenance menu will appear without a Delete Table item.
Similarly, if you wish to remove entire menus from the MapInfo Professional menu bar, you can do so by editing the Create Menu Bar statement that appears in the menus file. If MapInfo Professional is installed on a network, and you modify the menus file in the directory where MapInfo Professional is installed, the changes will apply to all MapInfo Professional users on the network. In some circumstances, you may want to create different menu structures for different network users. For example, you may want to eliminate the Delete Table command from the menu that appears for most of your users, but you may want that command to remain available to your network system administrator. To assign an individual user a customized menu structure, place a customized version of the menus file in that users home directory. For Windows users, the home directory is defined as the users private Windows directory (i.e., the directory where WIN.INI resides). To assign an individual user a customized menu structure, place a customized version of the menus file in that users home directory/folder. The menus file can be placed directly in the System directory, or in the Preferences directory within the System directory. When a user runs MapInfo Professional, it checks to see if a copy of the menus file exists in the users home directory. If a copy of the menus file is present in the users home directory, MapInfo Professional loads that set of menus. If there is no menus file in the users home directory, MapInfo Professional loads the menus file from the directory where it is installed.
MapBasic 10.5
92
User Guide
Chapter 6: Creating the User Interface Standard Dialog Boxes Thus, if you want different users to see two different versions of the menu structure, create two different versions of the menus file. Place the version that applies to most of your users in the directory where MapInfo Professional is installed. Place the version that applies only to individual users in the home directories of the individual users.
Displaying a Message
Use the Note statement to display a simple dialog box with a message and an OK button.
Selecting a File
Call the FileOpenDlg( ) function to display a standard File Open dialog box. If the user chooses a file, the function returns the name of the chosen file. If the user cancels out of the dialog box, the function returns an empty string.
MapBasic 10.5
93
User Guide
Chapter 6: Creating the User Interface Standard Dialog Boxes The FileOpenDlg( ) function produces a dialog box that looks like this:
The FileSaveAsDlg( ) function displays a standard File Save As dialog box, and returns the file name entered by the user.
Chapter 6: Creating the User Interface Custom Dialog Boxes Control StaticText Title "Enter string to find:" Control EditText Into s_searchfor Control OKButton Title "Search" Position 30, 30 Control CancelButton Position 90, 30 Because two of the Control clauses include Position clauses, the dialog boxs appearance changes:
Positions and sizes are stated in terms of dialog box units, where each dialog box unit represents one quarter of a characters width or one eighth of a characters height. The upper-left corner of the dialog box has the position 0, 0. The following Position clause specifies a position in the dialog box five characters from the left edge of the dialog box, and two characters from the top edge of the dialog box: Position 20, 16 A horizontal position of 20 specifies a position five characters to the right, since each dialog box unit represents one fourth of the width of a character. A vertical position of 16 specifies a position two characters down, since each dialog box unit spans one eighth of the height of a character. You can include a Position clause for every control in the dialog box. You also can specify Width and Height clauses to customize a controls size.
Control Types
The previous examples contained four types of controls (StaticText, EditText, OKButton, and CancelButton). The following illustration shows all of MapBasics dialog box control types.
MapBasic 10.5
96
User Guide
1 2 3
10 4 5 6 11 12
7 1 StaticText box 2 GroupBox 3 RadioGroup 4 ListBox 5 PopupMenu 6 Button 7 OKButton 8 EditText box 9 Picker (SymbolPicker) 10 MultiListBox 11 Checkbox 12 CancelButton
StaticText
A StaticText control is a non-interactive control that lets you include labels in the dialog box. For example: Control StaticText Title "Enter map title:" Position 5, 10
EditText
An EditText control is a boxed area where the user can type. For example: Control EditText Value "New Franchises, FY 95" Into s_title ID 1 Position 65, 8 Width 90
GroupBox
A GroupBox control is a rectangle with a label at the upper left corner. Use GroupBoxes for visual impact, to convey that other dialog box controls are related. For example: Control GroupBox Title "Level of Detail" Position 5, 30 Width 70 Height 40
MapBasic 10.5 97 User Guide
RadioGroup
A RadioGroup control is a set of radio buttons (i.e., a list of choices where MapBasic only allows the user to select one of the buttons at a time). For example: Control RadioGroup Title "&Full Details;&Partial Details" Value 2 Into i_details ID 2 Position 12, 42 Width 60
Picker
There are four types of Picker controls: PenPicker, BrushPicker, FontPicker, and SymbolPicker. Each Picker control lets the user select a graphical style (line, fill, font, or symbol). The illustration shown above includes a SymbolPicker control, showing a star-shaped symbol. For example: Control SymbolPicker Position 95, 45 Into sym_variable ID 3
ListBox
A ListBox control is a scrollable list from which the user can select one item. MapBasic automatically appends a vertical scroll bar to the right edge of the ListBox if there are too many list items to be displayed at one time. For example: Control ListBox Title "First Qrtr;2nd Qrtr;3rd Qrtr;4th Qrtr" Value 4 Into i_quarter ID 4 Position 5, 90 Width 65 Height 35
MultiListBox
A MultiListBox is similar to a ListBox, except that the user can shift-click or control-click to select two or more items from the list. For example: Control MultiListBox Title "Streets;Highways;Towns;Counties;States" Value 3 ID 5 Position 95, 90 Width 65 Height 35
PopupMenu
A PopupMenu appears as a text item with a down arrow at the right edge. As the user clicks on the control, a menu pops up, allowing the user to make a selection. For example: Control PopupMenu Title "Town;County;Territory;Entire state" Value 2
MapBasic 10.5 98 User Guide
Chapter 6: Creating the User Interface Custom Dialog Boxes Into i_scope ID 6 Position 5, 140
CheckBox
A CheckBox is a label with a box. The user can check or clear the box by clicking on the control. For example: Control CheckBox Title "Include &Legend" Into l_showlegend ID 7 Position 95, 140
Buttons
Button controls are perhaps the most common type of control that you will use, since almost every dialog box has at least one button. MapBasic provides special control types OKButton and CancelButton for creating OK and Cancel buttons. Control Button Title "&Reset" Calling reset_sub Position 10, 165 Control OKButton Position 65, 165 Calling ok_sub Control CancelButton Position 120, 165 Each dialog box should have no more than one OKButton or CancelButton control. Both controls are optional. However, as a general rule, every dialog box should have at least one OK and/or a Cancel button, so that the user has a way of dismissing the dialog box. If either control has a handler, MapBasic executes the handler procedure and then resumes executing the statements that follow the Dialog statement. Every type of control is described in detail in the MapBasic Reference Guide and online Help. For example, to read about ListBox controls, see Control Listbox.
MapBasic 10.5
99
User Guide
Chapter 6: Creating the User Interface Custom Dialog Boxes If you omit the Value clause, MapInfo Professional uses a default value. For example, CheckBox controls are checked by default. For more information about setting a Value clause, see the appropriate Control description (for example, Control CheckBox) in the MapBasic Reference Guide.
Chapter 6: Creating the User Interface Custom Dialog Boxes Most dialog box controls can have handler procedures (only GroupBox, StaticText, and EditText controls cannot have handlers). You also can specify a special handler procedure that is called once when the dialog box first appears. If your Dialog statement includes a Calling clause that is not part of a Control clause, the Calling clause assigns a handler procedure to the dialog box itself. The Alter Control statement may only be issued from within a handler procedure. Use Alter Control to disable, enable, show, hide, rename, or reset the current setting of a control. The Alter Control statement can also set which EditText control has the focus (i.e., which control is active). For more information, see Alter Control in the MapBasic Reference Guide or online Help.
MapBasic 10.5
101
User Guide
Chapter 6: Creating the User Interface Windows modeless dialog boxes, you may need to develop an application in another programming environment, such as Visual Basic, and call that application from within your MapBasic program (for example, using the Run Program statement).
Ordinarily, a dialog box terminates when the user clicks an OKButton or CancelButton control. There are times when the user should be allowed to continue using a dialog box after pressing OK or Cancel. For example, in some dialog boxes if the user presses Cancel, the application asks the user to verify the cancellation (Are you sure you want to lose your changes?). If the users response is No, the application should resume using the original dialog box. The Dialog Preserve statement lets you allow the user to continue using a dialog box after the OK or Cancel Button is clicked. You can only issue a Dialog Preserve statement from within the handler sub-procedure of either the OKButton or CancelButton control. The Dialog Remove statement halts a dialog box prematurely. When a controls handler procedure issues a Dialog Remove statement, the dialog box halts immediately. Dialog Remove is only valid from within a dialog box controls handler procedure. Dialog Remove can be used, for instance, to terminate a dialog box when the user double-clicks a ListBox control. The Named Views sample program (NVIEWS.MB) provides an example of allowing the user to double-click in a list.
Windows
A MapBasic application can open and manipulate any of MapInfo Professionals standard window types (Map windows, Browse windows, etc.). To open a new document window, issue one of these statements: Map, Browse, Graph, Layout, or Create Redistricter. Each document window displays data from a table, so you must have the proper table(s) open before you open the window. To open one of MapInfo Professionals other windows (for example, the Help window or the Statistics window), use the Open Window statement. Many window settings can be controlled through the Set Window statement. For example, you could use the Set Window statement to set a windows size or position. There are also other statements that let you configure attributes of specific window types. For example, to control the order of layers in a Map window, you would issue a Set Map statement. To control the display of a grid in a Browse window, you would issue a Set Browse statement.
MapBasic 10.5
103
User Guide
Chapter 6: Creating the User Interface Windows Each document window (Map, Browser, Layout, Graph, or Redistrict) has an Integer identifier, or window ID. Various statements and functions require a window ID as a parameter. For example, if two or more Map windows are open, and you want to issue a Set Map statement to modify the window, you should specify a window ID so that MapInfo Professional knows which window to modify. To obtain the window ID of the active window, call the FrontWindow( ) function. Note that when you first open a window (for example, by issuing a Map statement), that new window is the active window. For example, the OverView sample program issues a Map statement to open a Map window, and then immediately calls the FrontWindow( ) function to record the ID of the new Map window. Subsequent operations performed by the OverView application refer to the ID. A window ID is not a simple, ordinal number, such as 1, 2, etc. The number 1 (one) is not a valid window ID. To obtain a window ID, you must call a function such as FrontWindow( ) or WindowID( ). For example, to obtain the window ID of the first window that is open, call WindowID(1). To determine the number of open windows, call NumWindows( ). The WindowInfo( ) function returns information about an open window. For example, if you want to determine whether the active window is a Map window, you can call FrontWindow( ) to determine the active windows ID, and then call WindowInfo( ) to determine the active windows window type. To close a window, issue a Close Window statement.
Map Windows
A Map window displays mappable objects from one or more tables. When opening a Map window, you must specify the tables that you want to display; each table must already be open. The following statement opens a Map window: Map From world, worldcap, grid30 This example maps the objects from the World, Worldcap, and Grid30 tables.
MapBasic 10.5
104
User Guide
Chapter 6: Creating the User Interface Windows To add layers to a Map window, issue an Add Map Layer statement. To remove map layers from a Map window, issue a Remove Map Layer statement. If you want to temporarily hide a map layer, you do not need to remove it from the map; instead, you can use the Set Map statement to set that layers Display attribute to off. The Set Map statement is a very powerful statement that can control many aspects of a Map window. By issuing Set Map statements, your program can control map attributes that the user would control through the Map > Layer Control and Map > Options commands. For more information, see Set Map in the MapBasic Reference Guide. Use the Shade statement to create a thematic map (a map that uses color coding or other graphical devices to display information about the data attached to the map). The Shade statement lets you create the following of MapInfo Professionals styles of thematic maps: ranges, bar charts, pie charts, graduated symbols, dot density, or individual values. When you create a thematic map, MapInfo Professional adds a thematic layer to the affected window. To modify a thematic map, use the Set Shade statement. Use the Create Grid statement to create a thematic type that enables analysis unconstrained by pre-existing geographic boundaries. Surface themes provide a continuous color visualization for point data sets that you previously looked at as a point thematic or graduated symbol. An inverse distance weighted interpolator populates the surface values from your MapInfo Professional point table. This powerful thematic can be used in many industries like telco, retail analysis, insurance, traditional GIS areas, and many more. This new theme and grid format is supported by open APIs for additional grid formats and interpolators which allows customization by our developer community. Refer to the Create Grid statement in the MapBasic Reference Guide. To modify a surface thematic, use the Inflect clause of the Set Map statement. To change a Map windows projection, you can issue a Set Map statement with a CoordSys clause. Alternately, you can display a map in a specific projection by saving your table(s) in a specific projection (using the Commit TableAs statement). To control whether scroll bars appear on a Map window, issue a Set Window statement.
MapBasic 10.5
105
User Guide
Chapter 6: Creating the User Interface Windows Animation layers have the following restrictions: When you add an animation layer, it does not appear in the Layer Control window. The user cannot interact with the animation layer by clicking in the Map window. For example, the user cannot use the Info tool to click on a point in the animation layer. Each Map window can have only one animation layer. The animation layer automatically becomes the maps top layer. If you attempt to add an animation layer to a Map window that already has an animation layer, the new animation layer replaces the old one. Workspace files do not preserve information about animation layers. To terminate the animation layer processing, issue a Remove Map Layer Animate statement.
For example, suppose you are working with two tables: Roads (a table containing a street map), and Trucks (a table containing point objects, each of which represents a delivery truck). Suppose your Map window already contains both layers. If you want to turn the Trucks layer into an animation layer, you need to issue the following statement: Add Map Layer Trucks Animate However, you now have a problem: the Trucks layer now appears in the Map window twice-once as a conventional map layer, and once as an animation layer. Because the Trucks layer is still being displayed as a conventional layer, MapInfo Professional will not be able to perform fast screen updates. In other words, updates to the Map window will redraw as slowly as before, which defeats the purpose of the animation layer feature. The following example demonstrates how to handle this situation. Before you add the Trucks layer as an animation layer, turn off the display of the conventional Trucks layer: temporarily prevent screen updates Set Event Processing Off set the original Trucks layer so it wont display Set Map Layer "Trucks" Display Off add the Trucks layer to the map, as an animation layer Add Map Layer Trucks Animate allow screen updates again Set Event Processing On ' At this point, there are two Trucks layers in the ' Map window. However, the "conventional" Trucks layer
MapBasic 10.5 106 User Guide
Chapter 6: Creating the User Interface Windows ' is not displayed, so it will not slow down the display ' of the "animated" Trucks layer.
Browser Windows
A Browser window displays columns of table data. The following statement opens a simple Browser window that displays all the columns in the World table: Browse * From world The asterisk specifies that every column in the table should appear in the Browser. To open a Browser window that displays only some of the columns, replace the asterisk with a list of column expressions. For example, the following statement opens a Browser window that shows only two columns: Browse country, capital From world The Browse statement can specify column expressions that calculate derived values. For example, the following statement uses the Format$( ) function to create a formatted version of the World tables Population column. As a result, the second column in the Browser contains commas to make the population statistics more readable. Browse country, Format$(Population, ",#") From world If the Browse statement specifies a simple column name (for example, country), the Browser window allows the user to edit the column values (unless the table is read-only). However, if the Browse statement specifies an expression that is more complex than just a column name, the corresponding column in the Browser window is read-only. Thus, if you want to create read-only columns in a Browser window, you can do so by browsing an expression, rather than a simple column name. The expressions that you specify in the Browse statement appear as column headers across the top of the Browser window. The following statement shows how you can override the default column expression with an alias column header: Browse country, Format$(Population, ",#") "Pop" From world Because the String expression Pop appears after the column expression, Pop will be the column header that appears on the Browser window. You can also set the initial default position of the Browser window. The following example positions the initial display so that the second column of the fifth row is in the upper left position of the Browser display: Browse * From world Row 5 Column 2
Graph Windows
A Graph window contains a graph containing labels and values computed from a table. This sample displays a graph using one column for labels and another for data: Graph country, population From world
MapBasic 10.5
107
User Guide
Chapter 6: Creating the User Interface Windows The first item after the keyword Graph is the name of the column that provides labels for the data. Each following item is an expression that provides the graph with data. The example above is a simple expression in which the data is one column of the table. You can use any valid numeric expression.
Layout Windows
A Layout window represents a page layout. To open a Layout window, use the Layout statement. Most Layout windows contain one or more frame objects. To create a frame object, issue a Create Frame statement. Layout windows also can contain any type of Map object. For example, to place a title on the page layout, create a text object by issuing a Create Text statement. A Layout window can be treated as a table. For example, you can add objects to a Layout by issuing an Insert statement that refers to a table name such as Layout1. However, strictly speaking, the objects that appear on a layout are not saved in table format (although they are saved in workspace files). For more information on accessing a Layout window as if it were a table, see Working With Tables. Objects stored on Layout windows must use a Layout coordinate system, which defines object coordinates in terms of paper units such as inches or millimeters. For more information on Layout coordinates, see Graphical Objects.
Redistrict Windows
Use the Create Redistricter statement to begin a redistricting session. The Create Redistricter statement lets your program control all redistricting options that the user might configure through the Window > New Redistrict Window dialog box. Once a redistricting session has begun, you can control the Districts Browser by issuing Set Redistricter statements. To perform actions from the Redistrict menu, use the Run Menu Command statement. For example, to assign objects to a district (as if the user had chosen Redistrict > Assign Selected Objects), issue the following statement: Run Menu Command M_REDISTRICT_ASSIGN To end a redistricting session, close the Districts Browser by issuing a Close Window statement. Note that values in the base table change as objects are re-assigned from district to district. After a redistricting session, you must save the base table if you want to retain the map objects final district assignments. To save a table, issue a Commit statement. For more information about redistricting, see the MapInfo Professional documentation.
Message Window
You can use MapBasics Print statement to print text to the Message window. For example, the following statement prints a message to the Message window: Print "Dispatcher is now on line."
MapBasic 10.5 108 User Guide
Chapter 6: Creating the User Interface Windows Customizing the Info Window The Info window displays a row from a table. The user can edit a row by typing into the Info window. To control and customize the Info window, use the Set Window statement. The following picture shows a customized Info window:
The following program creates the customized Info window shown above. Include "mapbasic.def" Open Table "World" Interactive Select Country, Capital, Inflat_Rate + 0 "Inflation" From World Into World_Query Set Window Info Title "Country Data" Table World_Query Rec 1 Font MakeFont("Arial", 1, 10, BLACK, WHITE) Width 3 Units "in" Height 1.2 Units "in" Position (2.5, 1.5) Units "in" Front Note the following points about this example: Ordinarily, the Info windows title bar reads Info Tool. This program uses the Title clause to make the title bar read Country Data. To specify which row of data appears in the window, use the Set Window statements TableRec clause. The example above displays record number 1 from the World_Query table. (World_Query is a temporary table produced by the Select statement.) The Info window displays a box for each field in the record; the scroll-bar at the right edge of the window allows the user to scroll down through the fields. To limit the number of fields displayed, the example above uses a Select statement to build a temporary query table, World_Query. The World_Query table has only three columns; as a result, the Info window displays only three fields.
To make some, but not all, of the fields in the Info window read-only: 1. Use a Select statement to produce a temporary query table. 2. Set up the Select statement so that it calculates expressions instead of simple column values. The Select statement shown above specifies the expression Inflat_Rate + 0" for the third column value. (The Inflation string that follows the expression is an alias for the expression.) Select Country, Capital, Inflat_Rate + 0 "Inflation" 3. In the Set Window Info statement, use the Table Rec clause to specify which record is displayed. Specify a row from the query table, as in the example above. When a column in the
MapBasic 10.5 109 User Guide
Chapter 6: Creating the User Interface ButtonPads (Toolbars) query table is defined with an expression, the corresponding box in the Info window is read-only. (In the example above, the Inflation field is read-only.) 4. When the user types a new value into the Info window, MapInfo Professional automatically stores the new value in the temporary query table, and in the base table on which the query was based. You do not need to issue additional statements to apply the edit to the table. (However, you do need to issue a Commit statement if you want to save the users edits.) To make all fields in the Info window read-only, issue the following statement: Set Window Info ReadOnly All of the fields in the Info window are read-only when you display a table that is a join (such as a StreetInfo table) or a query table that uses the Group By clause to calculate aggregate values.
ButtonPads (Toolbars)
A ButtonPad is a resizable, floating window which contains one or more buttons. The user can initiate various types of actions by choosing buttons from a ButtonPad. The terms ButtonPad and toolbar mean exactly the same thing. The MapInfo Professional user interface refers to toolbars. For example, MapInfo Professionals Options menu has a Toolbars command, which lets the MapInfo Professional user show or hide toolbars. Meanwhile, the MapBasic language syntax refers to toolbars as ButtonPads. For example, use the Alter ButtonPad statement to show or hide a toolbar. MapInfo Professional provides several standard ButtonPads, such as the Main ButtonPad. A MapBasic program can add custom buttons to existing ButtonPads, or create entirely new ButtonPads.
MapBasic 10.5
110
User Guide
Chapter 6: Creating the User Interface ButtonPads (Toolbars) ToggleButton: When the user clicks on a ToggleButton, the button toggles between being checked (pushed in) and being unchecked (not pushed in). MapBasic calls the buttons handler procedure each time the user clicks on the ToggleButton. The Show/Hide Legend Window button is an example of a ToggleButton. Clicking on the button has an immediate effect: showing or hiding the Legend Window. Furthermore, there is a lasting change to the buttons status: the button toggles in or out. ToolButton: When the user clicks on a ToolButton, that button becomes the active tool, and remains the active tool until the user chooses a different tool. MapBasic calls the buttons handler procedure if the user clicks in a Map, Browse, or Layout window while the custom button is the selected tool. The Magnify tool is an example of a ToolButton. Choosing the tool does not produce any immediate effects; however, choosing the tool and then clicking in a Map window does have an effect.
Create ButtonPad
This statement creates a new ButtonPad and provides a custom icon for a button. You have to define both small and large sized buttons with resource file ids of n and n+1 respectively.
Alter ButtonPad
After creating a custom ButtonPad, your program can alter various attributes of the ButtonPad. The Alter ButtonPad statement lets you reposition, show, or hide a ButtonPad, or add or remove buttons to or from a ButtonPad. The Alter ButtonPad statement lets you modify any ButtonPad, even standard pads, such as Main. If your application needs only one or two custom buttons, you may want to add those buttons to the standard Main ButtonPad, instead of creating a new ButtonPad.
Alter Button
This statement modifies the status of a single button. Use the Alter Button statement to disable (deactivate) or enable (activate) a button, or to change which button is currently selected.
CommandInfo( )
Use the CommandInfo( ) function within a buttons handler procedure to query information about how the user has used the custom button. For example, if the user chooses a ToolButton and then clicks in a Map window, the CommandInfo( ) function can read the x- and y-coordinates of the location where the user clicked. If you create two or more buttons that call the same handler procedure, that procedure can call CommandInfo(CMD_INFO_TOOLBTN) to determine which button is in use.
MapBasic 10.5
111
User Guide
Chapter 6: Creating the User Interface ButtonPads (Toolbars) Thus, within a buttons handler procedure, you might call CommandInfo( ) several times: Once to determine which button the user has chosen; once to determine the x-coordinate of the location where the user clicked; once to determine the y-coordinate; and once to determine whether or not the user held down the shift key while clicking.
ToolHandler
ToolHandler, a special procedure name, gives you an easy way to add one button to the Main ButtonPad. If your MapBasic program includes a procedure named ToolHandler, MapBasic automatically adds one ToolButton to the Main ButtonPad. Then, if the user chooses the ToolButton, MapBasic automatically calls the ToolHandler procedure each time the user clicks in a Map, Browse, or Layout window. A MapBasic program cannot customize the button icon or draw mode associated with the ToolHandler procedure; the icon and cursor always use a simple + shape. If you need to specify a custom icon or cursor, use the Create ButtonPad or Alter ButtonPad statement instead of a ToolHandler procedure. If the user runs multiple MapBasic applications at one time, and each application has its own ToolHandler, each application adds its own button to the Main ButtonPad.
MapBasic 10.5
112
User Guide
Chapter 6: Creating the User Interface ButtonPads (Toolbars) The Icon clause tells MapBasic which icon to display on the custom button. The identifier, MI_ICON_ZOOM_QUESTION, is defined in the file icons.def. To see a list of standard MapInfo Professional icon identifiers, examine icons.def. The Calling clause tells MapBasic to call the button_prompt procedure whenever the user clicks on the custom button. The HelpMsg clause defines both a status bar help message and a ToolTip help message for the button. Help messages are discussed in Assigning Help Messages to Buttons on page 117. See the Create ButtonPad statement in the MapBasic Reference for image size considerations.
Chapter 6: Creating the User Interface ButtonPads (Toolbars) ToolButton Icon MI_ICON_LINE DrawMode DM_CUSTOM_LINE Cursor MI_CURSOR_CROSSHAIR Calling draw_via_button HelpMsg "Draws a line on a Map window\nDraw Line" Show End Sub Sub draw_via_button Dim x1, y1,x2, y2 As Float If WindowInfo(FrontWindow(),WIN_INFO_TYPE) <> WIN_MAPPER Then Note "This tool may only be used on a Map window. Sorry!" Exit Sub End If Determine map location where user clicked: x1 = CommandInfo(CMD_INFO_X) y1 = CommandInfo(CMD_INFO_Y) x2 = CommandInfo(CMD_INFO_X2) y2 = CommandInfo(CMD_INFO_Y2) Here, you could create objects based on x1, y1, x2, and y2. End Sub In this example, the Create ButtonPad statement includes the ToolButton keyword instead of the PushButton keyword. This tells MapBasic to make the custom button act like a drawing tool. The button definition includes a DrawMode clause, which tells MapBasic whether the user can drag after clicking with the tool. The example above uses the DM_CUSTOM_LINE drawing mode; therefore, the user is able to click and drag with the custom tool, just as you can click and drag when using MapInfo Professionals standard Line tool. When a tool uses the DM_CUSTOM_POINT mode, the user cannot drag after clicking. For a listing of all available drawing modes, see Alter ButtonPad in the MapBasic Reference Guide or online Help. The DrawMode clause also controls what the user sees while dragging. With the DM_CUSTOM_LINE mode, MapBasic draws a line between the cursor location and the point where the user first clicked. With the DM_CUSTOM_RECT mode, MapBasic draws a rectangular marquee while the user drags the mouse. Regardless of which DrawMode is used with a ToolButton, MapInfo Professional calls the buttons handler procedure after the user clicks and releases the mouse button. The handler procedure can call CommandInfo( ) to determine where the user clicked. If the user cancels the operation by pressing the Esc key, MapInfo Professional does not call the handler procedure.
MapBasic 10.5
114
User Guide
Chapter 6: Creating the User Interface ButtonPads (Toolbars) The keyword Icon is followed by a code from ICONS.DEF. For example, the following statement defines a custom button that uses the icon for MapInfo Professionals Info button. The code MI_ICON_INFO is defined in ICONS.DEF. Alter ButtonPad "Main" Add Separator Add PushButton Icon MI_ICON_INFO Calling procedure_name MapInfo Professional provides many built-in icons, most of which are not used in MapInfo Professionals standard user interface. To see a demonstration of the built-in icons, run the sample program Icon Sampler (ICONDEMO.MBX) and then choose an item from the Icon Sampler menu. To see the code for a particular icon, position the mouse over that icon. The buttons ToolTip shows you the icon code. You also can copy an icons code to the clipboard: 1. Run the Icon Sampler application (ICONDEMO.MBX). 2. Choose an item from the Icon Sampler menu. A custom ButtonPad appears.
3. Click on the button whose icon you want to use. A dialog box appears.
4. Press Ctrl-C (the Windows shortcut for the Copy command). 5. Click OK to dismiss the dialog box. 6. Switch to MapBasic. Press Ctrl-V (the shortcut for Paste) to paste the code into your program.
MapBasic 10.5
115
User Guide
Chapter 6: Creating the User Interface ButtonPads (Toolbars) The following handler procedure selects the town boundary region where the user clicked. To determine the coordinates where the user clicked, call CommandInfo( ). Then, to select objects at that location, issue a Select statement with a Where clause, and specify a geographic operator such as Contains. The following example selects all the town regions that contain the location where the user clicked. Sub t_click_handle Dim fx, fy As Float fx = CommandInfo(CMD_INFO_X) fy = CommandInfo(CMD_INFO_Y) Select * From towns Where obj Contains CreatePoint(fx, fy) End Sub Instead of using a Select statement, you could call the SearchPoint( ) or SearchRect( ) function to perform a search, and then call SearchInfo( ) to process the search results. For an example of this technique, see SearchInfo( ) in the MapBasic Reference Guide or online Help. Another approach would be to define a procedure called SelChangedHandler. If the user is running an application that contains a SelChangedHandler procedure, MapInfo Professional automatically calls that procedure every time the selection changes. The user could select objects by pointing and clicking with MapInfo Professionals standard Select tool (the arrow-shaped icon at the upper left corner of MapInfo Professionals Main ButtonPad), and your application could respond by issuing statements within the SelChangedHandler procedure.
MapBasic 10.5
116
User Guide
Chapter 6: Creating the User Interface ButtonPads (Toolbars) The first buttons Calling clause specifies M_TOOLS_SELECTOR, which is a numeric code defined in MENU.DEF. This code represents MapInfo Professionals Select button. Every standard MapInfo Professional button has a corresponding code in MENU.DEF. Because the second button is a custom button, its Calling clause specifies the name of a procedure, rather than a numeric code. Note that the custom button includes a DrawMode clause, but the Select button does not. When you place a standard button on a custom pad, you should omit the DrawMode clause, because each of MapInfo Professionals standard buttons already has a pre-defined draw mode. You should only specify a DrawMode clause when creating a custom ToolButton. CAUTION: ToolButtons and ToggleButtons are not interchangeable. You cannot convert one type of button to another type merely by replacing the ToolButton keyword with the ToggleButton keyword (or vice versa). ToolButtons return x/y coordinates in response to the user clicking on a window. ToggleButtons, however, do not return coordinates, and they respond as soon as the user clicks on the button.
If you include standard MapInfo Professional buttons in your custom ButtonPads, make sure that you do not accidentally change a ToolButton to a ToggleButton. To see how MapInfo Professionals standard buttons are defined, view the MapInfo Professional menus file, MAPINFOW.MNU. The menus file contains the Create ButtonPad statements that define MapInfo Professionals ButtonPads. You can copy button definitions out of MAPINFOW.MNU and paste them into your programs.
In earlier versions of MapInfo Professional, status bar help only appeared when the user clicked on a button. In version 4.0 and later, both the status bar help and ToolTip help appear when the user leaves the mouse cursor positioned over a toolbar button. Both types of help messages are defined through the HelpMsg clause, in the Create ButtonPad and Alter ButtonPad statements. Within the HelpMsg clause, you specify one string that contains the status bar help message, followed by the letters \n, followed by the ToolTip message. For example: Create ButtonPad "Custom" As PushButton Icon MI_ICON_ZOOM_QUESTION Calling generate_report HelpMsg "This button generates reports\nGenerate Report" Show
MapBasic 10.5 117 User Guide
Chapter 6: Creating the User Interface Integrating Your Application Into MapInfo Professional In this example, the custom buttons status bar help message is This button generates reports and its ToolTip message is Generate Report. To show or hide the status bar, use the StatusBar statement.
Chapter 6: Creating the User Interface Integrating Your Application Into MapInfo Professional Ordinarily, MapInfo Professional displays the Quick Start dialog box as soon as the user runs it (unless the user has cleared the Display Quick Start dialog box check box in the Startup Preferences dialog box). However, if you add the name of a MapBasic application to the command that launches MapInfo Professional, then the Quick Start dialog box will not appear. Depending on the nature of your application, this behavior may or may not be desirable. If you want your application to run automatically, without disabling the Quick Start dialog box, you may need to use a different method for loading your application. Instead of modifying the MapInfo Professional command line, you may want to create a special workspace, called the Startup workspace.
MapBasic 10.5
119
User Guide
Chapter 6: Creating the User Interface Performance Tips for the User Interface 1. Choose MapInfo Professionals Tools > Run MapBasic Program command to run the TextBox application. 2. Choose Tools > TextBox > About TextBox to display the About TextBox dialog box. 3. Click on the Auto-Load button on the About TextBox dialog box. MapInfo Professional displays a dialog box that lets you activate automatic the loading of the TextBox application. 4. Choose OK on the Enable Automatic Loading dialog box. MapInfo Professional displays a message indicating that the TextBox application is now configured to run automatically. Choose OK on the About TextBox dialog box. 5. Exit MapInfo Professional, then restart it. Note that in this new MapInfo Professional session, the TextBox application runs automatically; you do not need to choose Tools > Run MapBasic application. When you choose OK in step 4, the TextBox application adds a Run Application statement to the startup workspace file. If the startup workspace file does not exist, the TextBox application creates it. The maintenance of the startup workspace is handled by functions and procedures in the program module auto_lib.mb. Many of the sample programs that are bundled with MapInfo Professional contain the same functionality; for example, a MapInfo Professional user can set up the ScaleBar application to run automatically by choosing the Auto-Load button on the About ScaleBar dialog box. The auto_lib.mb program module is one of the sample programs included with MapBasic. If you want your application to include the Auto-Load feature, follow the instructions that appear in the comments at the top of auto_lib.mb.
MapBasic 10.5
Chapter 6: Creating the User Interface Performance Tips for the User Interface To suppress unnecessary redrawing of all MapInfo Professional windows, use the Set Event Processing Off statement. When you are finished updating various windows, issue a Set Event Processing On statement, and the screen will redraw once.
MapBasic 10.5
121
User Guide
MapBasic provides you with a full complement of statements and functions for working with tables. For instance, you can modify the structure of a table using the Alter Table statement, or locate a row in a table using Fetch. The Import statement lets you create a MapInfo table from a text file and the Export statement lets you export a table to a different format. This chapter introduces you to the MapBasic statements and functions that let you manage your MapInfo tables. Refer to the MapBasic Reference for more information about each statement and function.
Chapter 7: Working With Tables Opening Tables Through MapBasic However, you can use the TableInfo( ) function to determine the alias under which a table was opened, as shown in the following example: Include "mapbasic.def" Dim s_filename As String Open Table "states" Interactive s_filename = TableInfo(0, TAB_INFO_NAME) Browse * from s_filename The function call TableInfo(0, TAB_INFO_NAME) returns the alias name of the most recently opened table.
MapBasic 10.5
124
User Guide
MapBasic 10.5
125
User Guide
Using this syntax, you can write a MapBasic program that determines, at runtime, which column to reference. The tablename in a table reference is optional in statements in which the table name is already part of the statement. For instance, in the Browse statement you are required to specify column names and then the table name. Since the table name is explicitly specified in the statement (in the From clause), the column references at the beginning of the line do not need to include the tablename. Select Country, Population/1000000 From World Browse Country, Col2 From Selection The Select statement also has a From clause, where you name the table(s) to be queried. Column names that appear within a Select statement do not need the tablename. prefix if the Select statement queries a single table. However, if a Select statements From clause lists two or more tables, column references must include the tablename. prefix. For a general introduction to using the SQL Select statement, see the MapInfo Professional User Guide, or see Select in the MapBasic Reference Guide. There are instances in which you must use the COLn or the COL(n) column referencing method. In the example above, the Select statement identifies two columns; the latter of these columns is known as a derived column, since its values are derived from an equation (Population/1000000). The subsequent Browse statement can refer to the derived column only as col2 or as col(2), because the derived expression Population/1000000 is not a valid column name.
MapBasic 10.5
126
User Guide
Chapter 7: Working With Tables Reading Row-And-Column Values From a Table For example: Dim val_col As Alias val_col = "Inflat_Rate" Select * From world Where val_col > 4 MapBasic substitutes the contents of val_col (the alias, Inflat_Rate) into the Select statement in order to select all the countries having an inflation rate greater than 4 percent. The maximum length of the alias is 32 characters. In the example below, the sub-procedure MapIt opens a table, maps it, and selects all records from a specified column that have a value greater than or equal to a certain value. MapIt uses an Alias variable to construct column references that will be evaluated at runtime. Include "mapbasic.def" Declare Sub Main Declare Sub MapIt( ByVal filespec As String, ByVal col_name As String, ByVal min_value As Float ) Sub Main Call MapIt("C:\MAPINFOW\MAPS\WORLD.TAB", "population", 15000000) End Sub Sub MapIt( ByVal filespec As String, ByVal col_name As String, ByVal min_value As Float ) Dim a_name As Alias a_name = col_name Open Table filespec Map From TableInfo(0, TAB_INFO_NAME) Select * From TableInfo(0, TAB_INFO_NAME) Where a_name >= min_value End Sub In the MapIt procedure, a Select statement specifies an Alias variable (a_name) instead of an explicit column name. Note that the col_name parameter is not an Alias parameter; this is because MapBasic does not allow by-value Alias parameters. To work around this limitation, the column name is passed as a by-value String parameter, and the contents of the String parameter are copied to a local Alias variable (a_name). The example above demonstrates how an Alias variable can contain a string representing a column name (population). An Alias variable also can contain a full column reference in the form tablename.columnname. The following example demonstrates the appropriate syntax: Dim tab_expr As Alias Open Table "world" Fetch First From world tab_expr = "world.COL1" Note tab_expr The preceding Note statement has the same effect as the following statement:
MapBasic 10.5 127 User Guide
Chapter 7: Working With Tables Reading Row-And-Column Values From a Table Note world.COL1
Scope
The syntax tablename.columnname (for example, world.population) is similar to the syntax used to reference an element of a custom Type. MapBasic tries to interpret any name.name expression as a reference to an element of a Type variable. If the expression cannot be interpreted as a type element, MapBasic tries to interpret the expression as a reference to a column in an open table. If this fails, MapBasic generates a runtime error.
Chapter 7: Working With Tables Reading Row-And-Column Values From a Table The following example copies a graphical object from a table into an Object variable: Dim o_var As Object Fetch First From sites o_var = sites.obj For more information about graphical objects, see Graphical Objects.
Geocoding
To perform automatic geocoding: 1. Use the Fetch statement to retrieve an address from a table. 2. Use the Find Using statement and the Find statement to find the address. 3. Call CommandInfo( ) to determine how successful the Find statement was; call CommandInfo( ) again to determine x- and y-coordinates of the found location. 4. Create a point object by calling the CreatePoint( ) function or the Create Point statement. 5. Use the Update statement to attach the point object to the table. To perform interactive geocoding, issue the following statement: Run Menu Command M_TABLE_GEOCODE If you need to perform high-volume geocoding, you may want to purchase MapMarker, a dedicated geocoding product that is sold separately. MapMarker geocodes faster than MapInfo Professional and allows single-pass geocoding across the entire United States. MapBasic applications can control MapMarker through its programming interface. For more information on MapMarker, contact Pitney Bowes Software Inc. sales. The phone numbers appear at the beginning of this and other MapInfo product manuals.
MapBasic 10.5
129
User Guide
Chapter 7: Working With Tables Creating New Tables CustID Integer) File "C:\customer\Cust.tab" Create Map For CUST CoordSys Earth Create Index On CUST (CustID) Create Index On CUST(Name) You can also create a table by saving an existing table (for example, a selection) as a new table using the Commit statement, or by importing a table using the Import statement.
MapBasic 10.5
131
User Guide
The following program determines which tables are open and copies the table names into an array. Include "mapbasic.def" Dim i, table_count As Integer Dim tablenames() As String determine the number of open tables table_count = NumTables() Resize the array so that it can hold all of the table names. ReDim tablenames(table_count) Loop through the tables For i = 1 To table_count read the name of table # i tablenames(i) = TableInfo(i, TAB_INFO_NAME) display the table name in the message window Print tablenames(i) Next
MapBasic 10.5 132 User Guide
MapBasic 10.5
133
User Guide
MapBasic 10.5
134
User Guide
Chapter 7: Working With Tables Accessing the Cosmetic Layer To query the current selection, use the SelectionInfo( ) function. By calling SelectionInfo( ), you can determine how many rows are selected (if any) at the present time. If rows are currently selected, you can call SelectionInfo( ) to determine the name of the table from which rows were selected. You then can call TableInfo( ) to query additional information about the table. If your application includes a sub-procedure called SelChangedHandler, MapInfo Professional calls that procedure every time the selection changes. For example, you may want some of your applications custom menu items to only be enabled when rows are selected. To perform that type of selection-specific menu maintenance, create a SelChangedHandler procedure. Within the procedure, call SelectionInfo(SEL_INFO_NROWS) to determine if any rows are selected. Based on whether any rows are selected, issue an Alter Menu Item statement that enables or disables appropriate menu items. For more information on menu maintenance, see Creating the User Interface.
MapBasic 10.5
135
User Guide
Chapter 7: Working With Tables Multi-User Editing You can determine a Layout windows exact table name by calling the WindowInfo( ) function with the WIN_INFO_TABLE code. Objects stored on a Layout window use a special coordinate system, which uses paper units (units measured from the upper-left corner of the page layout). Any MapBasic program that creates or queries object coordinates from Layout objects must first issue a Set CoordSys statement that specifies the Layout coordinate system. For example, the TextBox sample program draws boxes (rectangle objects) around any currentlyselected text objects, regardless of whether the selected text objects are on a Map window or a Layout window. If the selected objects are Layout objects, TextBox issues a Set CoordSys Layout statement. When you are using MapInfo Professional interactively, MapInfo Professionals Statistics Window gives you an easy way of determining the table name that corresponds to a Layout window or to a Map windows Cosmetic layer. If you select an object in a Maps Cosmetic layer, and then show the Statistics Window (for example, by choosing Options > Show Statistics Window), the Statistics window displays a message such as, Table Cosmetic1 has 1 record selected. Similarly, if you select an object from a Layout window, the Statistics window displays, Table Layout1 has 1 record selected.
Multi-User Editing
If your MapBasic program works with tables in a multiple-user environment, you may encounter filesharing conflicts. Sharing conflicts occur because MapInfo Professional only allows one user to modify a table at a time. This section spells out the rules that govern MapInfo Professionals multi-user editing behavior. Read this section if you want to write a MapBasic program that allows multiple users to modify the same table at the same time.
Rule 1
A table may only be edited by one user at a time. Imagine two hypothetical users: User A and User B. Both users are attempting to use the same table, which is stored on a network. User A begins editing the table. (For example, User A adds new rows to the table.) Moments later, User B attempts to edit the same table. MapInfo Professional prevents User B from editing the table, and displays the message, Cannot perform edit. Someone else is currently editing this table. If User B is trying to edit the table through a MapBasic application, a runtime error occurs in the application.
MapBasic 10.5 136 User Guide
Chapter 7: Working With Tables Multi-User Editing As long as User A continues to edit the table, MapInfo Professional prevents User B from editing the same table. This condition remains until User A performs Save, Revert (discarding the edits), or Close Table. User B is allowed to read from the table that User A is editing. For example, User B can display the table in a Map window. However, User B will not see the edits made by User A until User A performs a Save.
Rule 2
Users cannot read from a table while it is being saved. After editing the table, User A chooses the File > Save Table command. Then, while the Save operation is still underway, User B attempts to read data from the table. As long as the Save is underway, MapInfo Professional prevents User B from accessing the table at all. MapInfo Professional displays a dialog box (on User Bs computer) with the message, Cannot access file <tablename>.DAT for read. The dialog box contains Retry and Cancel buttons, with the following meaning: Retry If User B clicks Retry, MapInfo Professional repeats the attempt to read from the file. The Retry attempt will fail if the Save is still underway. The user can click the Retry button repeatedly. After the Save operation finishes, clicking the Retry button succeeds. Cancel If User B clicks Cancel, MapInfo Professional cancels the operation, and the Retry/Cancel dialog box disappears. If User B was loading a workspace when the sharing error occurred, clicking Cancel may halt the loading of the rest of the workspace. For example, a workspace contains Open Table statements. If the Open Table statement was the statement that caused the sharing conflict, and if the user cancels the Retry/Cancel dialog box, MapInfo Professional will not open the table. Subsequent statements in the workspace may fail because the table was not opened.
Rule 3
A Save cannot be started while the table is being read by other users. If other users are reading the table at the exact moment that User A chooses File > Save Table, the Save Table command cannot proceed. MapInfo Professional displays the message, Cannot open file <tablename>.DAT for writing. The dialog box contains Retry and Cancel buttons, with the following meaning:
MapBasic 10.5
137
User Guide
Chapter 7: Working With Tables Multi-User Editing Retry If User A clicks Retry, MapInfo Professional repeats the attempt to save the table. The user can click the Retry button repeatedly. Clicking the Retry button will only succeed if the other users have finished reading from the table. Cancel If User A clicks Cancel, MapInfo Professional cancels the Save operation, and the Retry/Cancel dialog box disappears. At this point, the table has not been saved, and the edits will not be saved unless User A chooses File > Save Table again.
Function MakeNewRow(ByVal new_name As String) As Logical turn off automatic retries Set File Timeout 0 turn off window redraws Set Event Processing Off
MapBasic 10.5 138 User Guide
enable error-trapping OnError Goto trap_the_error Add a new row, and save the new row immediately. Insert Into Sitelist ("Name") Values ( new_name ) Commit Table Sitelist Set return value to indicate success. MakeNewRow = TRUE exit_ramp: Set Event Processing On Exit Function trap_the_error: The program jumps here if the Insert or Commit statements cause runtime errors (which will happen if another user is already editing the table). If Ask("Edit failed; try again?", "Yes", "No") Then ... then the user wants to try again. Resume 0 Else the user does not want to retry the operation. If the Insert succeeded, and were getting an error during Commit, we should discard our edits. Rollback Table Sitelist set functions return value to indicate failure: MakeNewRow = FALSE Resume exit_ramp End If End Function Note the following points: When you modify a shared table, try to minimize the amount of time that the table has unsaved edits. In the example above, the Commit statement follows immediately after the Insert statement, so that there is very little time during which the table has unsaved edits. The example uses Set Event Processing Off to suspend event processing; as a result, MapInfo Professional will not redraw any windows during the edit. If we did not suspend event processing, the Insert statement might cause MapInfo Professional to redraw one or more windows, and the window redraw could conceivably trigger a sharing conflict (for example, because other tables in the same Map window may have a sharing conflict). This function sets file-timeout to zero. The procedure that calls this function may need to reset file-timeout to its previous value.
MapBasic 10.5
139
User Guide
Because each table consists of several component files, you must be very careful when renaming a table. To rename a table, choose MapInfo Professionals Table > Maintenance > Rename Table command, or issue the MapBasic Rename Table statement.
MapBasic 10.5
140
User Guide
Chapter 7: Working With Tables Raster Image Tables In many ways, a raster image table is just like any other table. To open a raster image table, use an Open Table statement. To display a raster image table in a Map window, issue a Map statement. To add a raster image table to an existing map, issue an Add Map Layer statement. However, you cannot perform a Select operation on a raster image table. To determine if a table is a raster table, call TableInfo( ) with the TAB_INFO_TYPE code. If the table is a raster table, TableInfo( ) returns the code TAB_TYPE_IMAGE. As a rule, MapInfo Professional does not alter the original image file on which a raster table is based. Therefore: If you use the Drop Table statement to delete a raster table, MapInfo Professional deletes the table file, but does not delete the image file on which the table is based. If you use the Rename Table statement on a raster table, MapInfo Professional renames the table file, but does not rename the image file on which the table is based. If you use the Commit statement to copy a raster table, MapInfo Professional copies the table file but does not copy the image file on which the table is based.
A raster image tables .tab file is created when a user completes MapInfo Professionals Image Registration dialog box. If you need to create a .tab file for a raster image through a MapBasic program, create the file using standard file input/output statements: create the file using the Open File statement, and write text to the file using the Print # statement; see example below. The following program creates a table file to accompany a raster image file. This program assigns dummy coordinates, not true geographic coordinates. Therefore, the final table will not be suitable for overlaying vector map layers. However, if the raster image is a non-map image (as a company logo), the use of non-geographic coordinates is not a problem. Include "mapbasic.def" Declare Sub Main Declare Function register_nonmap_image(ByVal filename As String, ByVal tablename As String) As Logical Sub Main Dim fname, tname As String fname = "c:\data\raster\photo.gif" name of an existing image tname = PathToDirectory$(fname) + PathToTableName$(fname) + ".tab" name of table to create If FileExists(tname) Then Note "The image file is already registered; stopping." Else If register_nonmap_image(fname, tname) Then Note "Table file created for the image file: " + fname + "." Else Note "Could not create table file." End If End If End Sub Function register_nonmap_image( ByVal filename As String, ByVal tablename As String) As Logical register_nonmap_image = FALSE OnError GoTo handler Open File tablename For Output As #1 FileType "MIta" Print #1, "!Table"
MapBasic 10.5 141 User Guide
Chapter 7: Working With Tables Working With Metadata Print #1, "!Version 300" Print #1, "!charset Neutral" Print #1 Print #1, "Definition Table" Print #1, " File """ + filename + """" Print #1, " Type ""RASTER"" " Print #1, " (1,1) (1,1) Label ""Pt 1"", " Print #1, " (5,1) (5,1) Label ""Pt 2"", " Print #1, " (5,5) (5,5) Label ""Pt 3"" " Print #1, " CoordSys NonEarth Units ""mm"" " Print #1, " Units ""mm"" " Print #1, " RasterStyle 1 45" Brightness; default is 50 Print #1, " RasterStyle 2 60" Contrast; default is 50 Close File #1 register_nonmap_image = TRUE set function return value last_exit: Exit Function handler: Close File #1 Resume last_exit End Function
MapBasic 10.5
142
User Guide
Sample Key Name "\Copyright Notice" "Info" "Info Author" "Info\Date\Start" "Info\Date\End" "IsReadOnly" Note the following points:
Sample Key Value Copyright 2008 Pitney Bowes Mapinfo Corp." "Tax Parcels Map" "Meghan Marie" "12/14/01" "12/31/01" "FALSE"
Spaces are allowed within key names and within key values. You can define a hierarchy of keys by using key names that have two or more backslash characters. In the table above, several of the keys belong to a hierarchy that starts with the \Info key. Arranging keys in hierarchies allows you to work with an entire hierarchy at a time (for example, you can delete an entire hierarchy with a single statement). \IsReadOnly is a special key, reserved for internal use by MapInfo Professional. When you add metadata to a table, MapInfo Professional automatically creates the \IsReadOnly key. Do not attempt to modify the \IsReadOnly key. The table above shows each string within quotation marks to emphasize that they are string values. However, when you retrieve keys from a table, the strings retrieved by MapBasic do not actually include quotation marks.
Chapter 7: Working With Tables Working With Metadata Metadata Table table_name Dropkey "\Info\Author" The following statement deletes an entire hierarchy of keys at one time. All keys whose names start with \Info\ will be deleted. Metadata Table table_name Dropkey "\Info" Hierarchical When you use the Metadata statement to write or delete metadata, the changes take effect immediately. You do not need to perform a Save operation. You also can use the Metadata statement to read the metadata from a table, even if you do not know the names of the keys. To read a tables metadata: 1. Issue a Metadata TableSetTraverse statement to initialize a traversal. 2. Issue a Metadata TraverseNext statement to retrieve a key. This statement retrieves the keys name into one string variable, and retrieves the keys value into another string variable. 3. Continue to issue Metadata TraverseNext statements to retrieve additional keys. Typically, this statement is issued from within a loop. Once you have exhausted the keys, Metadata TraverseNext returns an empty string as the key name. 4. Terminate the traversal by issuing a Metadata TraverseDestroy statement. This action releases the memory used by the traversal. The following example shows how to traverse a tables metadata. Sub Print_Metadata(ByVal table_name As String) Dim i_traversal As Integer Dim s_keyname, s_keyvalue As String Initialize the traversal. Specify "\" as the starting key, so that the traversal will start with the very first key. Metadata Table table_name SetTraverse "\" Hierarchical Into ID i_traversal Attempt to fetch the first key: Metadata Traverse i_traversal Next Into Key s_keyname Into Value s_keyvalue Now loop for as long as there are key values; with each iteration of the loop, retrieve one key, and print it to the Message window. Do While s_keyname <> "" Print " " Print "Key name: " & s_keyname Print "Key value: " & s_keyvalue Metadata Traverse i_traversal Next Into Key s_keyname Into Value s_keyvalue Loop
MapBasic 10.5
144
User Guide
Chapter 7: Working With Tables Working With Seamless Tables Release this traversal to free memory: MetaData Traverse i_traversal Destroy End Sub For a complete listing of the syntax of the Metadata statement, see the MapBasic Reference Guide or online Help.
MapBasic 10.5
145
User Guide
The first column in a seamless table contains table names. The second column contains descriptions, which appear in the user interface. The table names in the first column may contain directory paths. You can omit the directory paths if the base tables are in the same directory as the seamless table, or if the base tables can be located by the Search Directories path (which is specified as a Preference, in the Directory Preferences dialog box). Every row in a seamless table has a map object attached to it, just as objects are attached to rows in conventional tables. However, the objects in a seamless table are not intended for display. Each row in a seamless table has a rectangle object, which defines the minimum bounding rectangle (MBR) for the table named in the first column. When a user displays a seamless table in a Map window, MapInfo Professional compares the Map windows current extents against the MBRs stored in the table. MapInfo Professional only opens the base tables when necessary (i.e., when the area currently visible in the Map window intersects the tables MBR).
Chapter 7: Working With Tables Accessing DBMS Data You cannot simultaneously select objects from more than one base table in a seamless table. The MapBasic Find statement cannot search an entire seamless table; the Find statement can only work with one base table at a time. You cannot make a seamless table editable in a Map window. You cannot create a thematic map for a seamless table.
Chapter 7: Working With Tables Accessing DBMS Data Server hdbc Disconnect This statement closes the connection and frees all resources associated with it. The following chart describes the sequence in which SQL MapBasic Server statements can be issued. There are some statements that require no connection information (for example, Server_NumDrivers( )), some that require only a connection handle (for example, Server Commit), and some that require a statement handle (for example, Server Fetch).
You can download an entire table, some rows and columns, or a result set from an ODBC data source using the Into feature of the MapBasic statement Server Fetch. However, any updates applied to the downloaded table are not applied back to the server database table. Updating remote databases is accomplished by the Save File statement.
MapBasic 10.5
148
User Guide
Chapter 7: Working With Tables Accessing/Updating Remote Databases with Linked Tables A Note about SQL Server 2008 Support SQL Server 2008 (SQL Server Spatial) provides a different ODBC driver for Windows Vista. A Windows Vista user must use the x64 and Itanium versions of sqlncli.msi, which installs the 64-bit and 32-bit versions of SQL Server Native Client, on your 64-bit Windows operating system To download the appropriate sqlncli.msi, see: http://msdn.microsoft.com/en-us/library/ms131321.aspx
Chapter 7: Working With Tables Performance Tips for Table Manipulation Concurrency control is accomplished with the Automatic/Interactive clause of the Commit Table statement. When the data is saved, a connection with the remote database is re-established, editing conflicts are resolved, and the changed data is written to the RDBMS. A linked table is created with the MapBasic statement Server Link Table. Linked tables contain information to re-establish connections and identify the remote data to be updated. This information is stored as metadata in the tab file. An unedited linked table can be refreshed with current data from the remote database without respecifying the connection data, query, and table. A linked table is refreshed with the MapBasic statement Server Refresh. A linked table can be unlinked with the MapBasic statement Unlink. Unlinking a table removes the link to the remote database. The end product is a normal MapInfo base table. Using MapInfo Professionals spatial indexing, users will be able to store and retrieve points in any database; or spatial objects in supported spatial objects. See Making a Remote Table Mappable.
MapBasic 10.5
150
User Guide
Using Sub-Selects
The Select statement can include a Where clause that performs a sub-select, as described in the MapBasic Reference Guide. However, you may find it faster to perform two non-nested Select statements, instead of one nested SelectWhere (Select ) statement. If you perform a sub-select of this type: ... Where x = Any( Select ...) ... then MapInfo Professional does optimize the query performance, but only if column x is indexed.
MapBasic 10.5
152
User Guide
File Input/Output
In MapBasic, there is an important distinction between managing files and managing MapInfo tables. The preceding chapter describes how MapBasic lets you manage tables. This chapter describes how you manage files that are not tables.
Regardless of which type of file i/o you will perform, the first step to performing file i/o is to open the file you want to use. In MapBasic, you open a file using the Open File statement. This statement has several optional clauses; which clauses you need to use depends on your specific situation. The following statement opens a text file for sequential input: Open File "settings.txt" For Input As #1 When you open a file, you specify a file number; in the example above, the number is one (1). Later statements in your program refer to the same number that you specified in the Open File statement. For example, to read text from the file into a String variable, you could issue a Line Input statement, and the Line Input statement would refer to the same file number (#1) as the Open File statement: Line Input #1, s_nextline If you need to have two or more files open at the same time, make sure that each file is opened under a different number. In some situations, you may need to create a new file in which to store your data. To create a new file, issue an Open File statement that includes the For Output clause: Open File "workfile.txt" For Output As #2 Alternately, you can specify For Append in the Open File statement. With Append mode, MapBasic creates the file if it does not already exist, or MapBasic lets you append data to the file if it already does exist. When you are finished reading from or writing to a file, issue a Close File statement. For example: Close File #1
MapBasic 10.5
154
User Guide
Chapter 8: File Input/Output Sequential File I/O The number parameter is the same identification number assigned to the file in the Open File statement. The pound sign (#) is optional. You do not need to execute a save command to save a file that was created or modified through file input/output. You are done modifying the file as soon as you issue the Close File statement. (MapBasic does provide a Save File statement, but its purpose is to let you copy a file, not save changes to a file.) There are many ways in which programs can generate runtime errors during file i/o. If the Open File statement specifies the wrong file name, or if you attempt to open a file for output, but the file is flagged as read-only, a runtime error will occur. If your program writes data to a file, the program could generate a runtime error if the program runs out of disk space. If you try to open a file for output, but that file is currently being modified by another network user, your program will generate a runtime error. If you are developing an application that performs file input/output, you should build error-handling routines into your program to detect and correct error conditions, and you should test your application under conditions likely to cause problems (for example, out of disk space). For information on how to create an error handler, see Debugging and Trapping Runtime Errors. In some circumstances, you can prevent errors from happening by calling appropriate functions. For example, before you issue an Open File statement, you can call the FileExists( ) function to determine whether the file exists. Also, if your program needs to create a temporary, working file, but you do not know what name or directory path to assign to the file (because you do not know the names of your users directories), call the TempFileName$( ) function. Other statements that are related to file i/o: The Kill statement deletes a file. The Save File statement saves a copy of a file. The Rename File statement changes the name of a file. Functions such as ProgramDirectory$( ), HomeDirectory$( ) and ApplicationDirectory$( ) let you determine different directory paths at runtime. For example, to build a string representing the name of a file that exists in the MapInfo Professional directory (for example, the Startup workspace), when you do not know the name of the directory, call ProgramDirectory$( ), to determine where MapInfo Professional is installed.
MapBasic 10.5
155
User Guide
Chapter 8: File Input/Output Sequential File I/O For example, the Named Views application reads data that is formatted in the following manner: "New York", -75.75, 42.83, 557.5 "Texas", -100.2, 31.29, 1200 Each line of the text file contains four values: a name, an x-coordinate, a y-coordinate, and a zoom distance. The Named Views application uses the following Input # statement to read each line into four separate variables: Input #1, vlist(tot).descript, vlist(tot).x, vlist(tot).y, vlist(tot).zoom The vlist variable is an array of custom type variables. When you read data sequentially, you need to test to see whether each read was successful. After your program has read the entire contents of the file, if you attempt to read further the read operation will fail. To test whether a read operation was successful, call the EOF( ) function (end-of-file) after each input operation. If the EOF( ) function returns a value of FALSE, then you have not yet exhausted the contents of the file (which means that your read was successful). When the EOF( ) function returns TRUE, you are at the end of the file. Reading the last line of the file does not cause the end-of-file condition. The EOF( ) function will only return TRUE after you have attempted to read past the end of the file. To create a file that contains a comma-separated list of expressions, issue an Open File statement with the For Output clause or the For Append clause. After opening the file, use the Write # statement to write data to the file. In the Write # statement, you can specify a comma-separated list of expressions to be written to each line in the file. For example, the Named Views application issues the following Write # statement (within a loop) to create a file with the four values (name, x, y, and zoom) shown above: Write #1, vlist(i).descript, vlist(i).x, vlist(i).y, vlist(i).zoom The Write # statement encloses each string expression in double-quotation marks within the file, as shown in the example above (New York). In some situations, using the Write # statement may be inappropriate, because you may not want text to be enclosed in quotation marks. To write text to a file without quotation marks, use Print # instead of Write #. If you want to read an entire line into one String variable, use the Line Input # statement. Use the Print # statement to create a file that can later be read using the Line Input # statement. For an example of using Print # and Line Input # to read or write an entire line at once, see the sample program auto_lib.mb. The auto_lib program reads and writes MapInfo workspace files (specifically, the startup workspace file). You cannot write to a sequential file that was initially opened for input and you cannot read from a sequential file that was initially opened for output.
Chapter 8: File Input/Output Platform-Specific & International Character Sets Open File "datafile.dat" For Random As #1 Len = 80 When you open a file in Random mode, you include a Len clause that indicates the number of bytes in each line in the file. Note that any text file contains end-of-line terminators; invisible characters that are embedded in the file to mark the end of each line. The line length specified in the Len clause (80 in the example above) specifies the exact number of characters in each record, including any end-of-line terminators (for example, carriage-return/line-feed characters). After you have opened a file for random access, you can read from or write to the file using the Get and Put statements. See the MapBasic Reference Guide for more information about these statements.
MapBasic 10.5
157
User Guide
Chapter 8: File Input/Output Platform-Specific & International Character Sets Professional will correctly interpret data while reading from (or writing to) the file. For a listing of character set names that can be used in a CharSet clause, see CharSet in the MapBasic Reference Guide.
Each of these functions uses the file number assigned in the Open File statement as an argument. For more information, see the MapBasic Reference Guide or online Help.
MapBasic 10.5
158
User Guide
Graphical Objects
Much of MapBasics power lies in its ability to query and manipulate map objectsarcs, ellipses, frames, lines, points, polylines, rectangles, regions, rounded rectangles, and text objects. This chapter discusses how a MapBasic program can query, create, and modify the objects that make up a map. Note, however, that you need to understand the principles of MapInfo tables before you can understand how MapBasic can store objects in tables. If you have not already done so, you may want to read Working With Tables before reading this chapter.
MapBasic 10.5
160
User Guide
Chapter 9: Graphical Objects Using the Obj Column The following statement creates a query table with state abbreviations and the area of each state; the Obj column is used as one of the parameters to the Area( ) function: Select state, Area(obj, "sq mi") From states The next example creates a one-row table with the total miles of highway in California: Select Sum(ObjectLen(obj, "mi")) From highways Where obj Within (Select obj From states Where state = "CA") Some rows do not contain map objects. For example, if you open a database file as a MapInfo table and geocode the table, the geocoding process attaches point objects to the rows in the table. However, if some of the rows were not geocoded, those rows will not have map objects. To select all the rows that do not have objects, use the condition Not obj in the Select statements Where clause. The next statement selects all rows that do not have map objects: Select * From sites Where Not obj
Chapter 9: Graphical Objects Querying An Objects Attributes If you list the outlets table first in the From clause, as shown below, the Select statements results table will contain point objects (outlets), rather than state regions: Select * From outlets, states Where outlets.state = states.state Map From selection Each row in a table can contain only one object. Note, however, that an individual object can contain multiple parts. A region object can contain many polygons; thus, a group of islands can be represented as a single region object. Similarly, a polyline object can contain many sections. To determine the number of polygons in a region object or the number of sections in a polyline object, select the object, and choose MapInfo Professionals Edit > Get Info command. To determine the number of sections or polygons from within a program, call the ObjectInfo( ) function with the OBJ_INFO_NPOLYGONS code.
Chapter 9: Graphical Objects Querying An Objects Attributes Many of the standard MapBasic functions take objects as arguments, and return one piece of information about the object as a return value. For example, the Area( ), Perimeter( ), and ObjectLen( ) functions take object parameters. The example below calculates the area of a flood zone: Dim floodarea As Float Open Table "floodmap" Fetch First From floodmap floodarea = Area(floodmap.obj, "sq km") Note that labels are not the same as text objects. To query a text object, you call functions such as ObjectInfo( ). To query a label, you call functions such as Labelinfo( ). Labels are discussed in Working With Map Labels on page 176.
Object Style
Chapter 9: Graphical Objects Querying An Objects Attributes Dim b1, b2 As Brush b1 = MakeBrush(2, 255, 0) b2 = CurrentBrush() If b1 = b2 Then Note "The two brush styles are equal." End If If you need to compare two styles, use the Str$( ) function to convert each style into a string expression. For example, the following statement compares two Brush values: If Str$(b1) = Str$(b2) Then ... If you need to compare specific elements of a style (for example, to see whether two Symbol styles have the same point size), use the StyleAttr( ) function to extract individual style elements (color, etc.), and then compare the individual elements.
A Font style includes a font name, such as Courier or Helvetica. Font names may be different on each hardware platform; for example, Helv and TmsRmn (or Times New Roman) in the Microsoft Windows environment are called Helvetica and Times on the Sun platforms. Helvetica, Times and Courier are recognized in a MapBasic Font clause regardless of the platform that is in use at runtime.
MapBasic 10.5
164
User Guide
Stacked Styles
You can stack styles for a layer, so that they become a list of styles drawn on top of each other, to create a more complex or interesting looking map feature. You can stack styles for points, polylines, and polygon features. This is especially useful for polyline styles. Figure 1 shows a sample line using one of MapInfo's interleaved line styles. Figure 2 shows the same sample using a stacked line style. Figure: Figure 1: Figure: Figure 2:
Stacked styles create more meaningful display styles for your application without having to add your data as multiple layers in a map. You can define as many styles in a stacked style as you want. However, the more styles you define the more you will impact the map's rendering performance. Typically, most cartographic maps would use two or three styles in a stacked style to draw features.
Chapter 9: Graphical Objects Querying An Objects Attributes To create stacked styles for Layer Display Overrides using MapBasic, see the MapBasic Reference for the Set Map statement. To query stacked style attributes, refer to new functions in the What's New section of the MapBasic Reference.
Set Map Layer 1 display Global Global Symbol (32,16777136,24), Symbol (36,255,14)
Example with a Polygon (Region) A stacked region style could be used to create a fill that uses two colors and two different line patterns.
Set Map Layer 1 Display Global Global Brush (4,0,16777215), Brush (5,16711680)
Style Variables
MapBasic provides style variable typesPen, Brush, Symbol, and Fontthat correspond to object style attributes. There are several ways you can assign a style to a style variable: Build a style expression by calling MakePen( ), MakeBrush( ), MakeFont( ), MakeSymbol( ), MakeCustomSymbol( ), or MakeFontSymbol( ), and assign the value to the style variable. These functions allow you to explicitly specify the desired styles. For example, the ScaleBar sample program calls MakeBrush( ) to build black and white brush expressions, so that the scale bar can have alternating blocks of black and white. Call CurrentPen( ), CurrentBrush( ), CurrentFont( ), or CurrentSymbol( ), and assign the return value to the style variable. These functions read the current styles (i.e., the styles that appear if you choose MapInfo Professionals Options > Line Style, Region Style, Symbol Style, or Text Style command when there are no objects selected). Call ObjectInfo( ) to determine the style of an existing object, and assign the return value to a style variable. Let the user choose a style through a dialog box. If a dialog box contains a PenPicker, BrushPicker, SymbolPicker, or FontPicker control, the user can choose a style by clicking on the control. For more information on dialog boxes, see Creating the User Interface.
166 User Guide
MapBasic 10.5
Chapter 9: Graphical Objects Querying An Objects Attributes The following example demonstrates how to call the MakePen( ) function to construct a Pen style. The Pen style value is assigned to a Pen variable. Dim p_var as Pen p_var = MakePen(1, 10, RGB(128, 128, 128)) The MakePen( ) functions arguments define the pen style: 1 signifies that the style is one pixel wide, 10 signifies a pattern (dotted), and the RGB( ) function call specifies a color. For more information about the three parameters that make up a pen style (including a chart of all available line patterns), see Pen clause in the MapBasic Reference Guide or online Help. Similarly, for more information about Brush, Font, or Symbol options, see Brush clause, Font clause, or Symbol clause. The following example demonstrates how to read an existing objects Pen style into a Pen variable: p_var = ObjectInfo(obj_var, OBJ_INFO_PEN) Once you have stored a Pen expression in a Pen variable, you can use the Pen variable within an object creation statement: Create Line Into Variable obj_var (-73, 42) (-74, 43) Pen p_var The function StyleAttr( ) returns one component of a particular style. For example, the TextBox sample program displays a dialog box that lets the user choose a pen style; the selected style is stored in the Pen variable, pstyle. TextBox then issues the following statement to read the Pen styles color component into an Integer variable (line_color): line_color = StyleAttr(pstyle, PEN_COLOR) Colors are stored internally as integer numbers. For instance, black is 0 and blue is 255. The RGB( ) function calculates the color value from quantities of red, green, and blue that you specify. For instance, the function call RGB(0, 255, 0) returns the color value for green. Use the RGB( ) function where a color is called for. For example: highway_style = MakePen(2, 2, RGB(0, 0, 255)) Alternately, instead of calling RGB( ) you can use one of the standard color definition codes (BLACK, WHITE, RED, GREEN, BLUE, YELLOW, CYAN, and MAGENTA) defined in mapbasic.def.
MapBasic 10.5
167
User Guide
Chapter 9: Graphical Objects Querying An Objects Attributes The following example adds a custom button to the Tools toolbar. If you select a point object and then click the custom button, this program selects all point objects in the same table that have the same color. Include "mapbasic.def" Declare Sub Main Declare Sub SelectPointsByColor() Sub Main Add a custom button to the Tools toolbar. Alter ButtonPad "Tools" Add PushButton Calling SelectPointsByColor HelpMsg "Select points of same color\nSelect By Color" End Sub Sub SelectPointsByColor Dim i_color, i_open As Integer Dim symbol_style As Symbol Dim object_name, table_name As String Note how many tables are currently open. i_open = NumTables() Determine the name of the table in use. table_name = SelectionInfo(SEL_INFO_TABLENAME) If table_name = "" Then ... then nothing is selected; just exit. Exit Sub End If Exit if the selection is in a non-mappable table. If Not TableInfo(table_name, TAB_INFO_MAPPABLE) Then Exit Sub End If See whether the selected object is a Point. If it is a Point, determine its Symbol and Color. Fetch First From Selection object_name = Str$(Selection.obj) If object_name = "Point" Then symbol_style = ObjectInfo(Selection.obj,OBJ_INFO_SYMBOL) i_color = StyleAttr(symbol_style, SYMBOL_COLOR) End If Accessing "Selection.obj" may have caused MapInfo Professional to open a temporary table called Query1 (or Query2...). Lets close that table, just to be tidy. If NumTables() > i_open Then Close Table TableInfo(0, TAB_INFO_NAME) End If If object_name <> "Point" Then ...the selected object isnt a point; just exit.
MapBasic 10.5 168 User Guide
Chapter 9: Graphical Objects Creating New Objects Exit Sub End If Select all the rows that contain point objects. Select * From table_name Where Str$(Obj) = "Point" Into Color_Query_Prep NoSelect Select those point objects that have the same color as the original object selected. Select * From Color_Query_Prep Where StyleAttr(ObjectInfo(obj,OBJ_INFO_SYMBOL),SYMBOL_COLOR) = i_color Into Color_Query Close Table Color_Query_Prep End Sub This example works with point objects, but the same techniques could be used with other object types. For example, to work with region objects instead, you would test for the object name Region instead of Point, and call ObjectInfo( ) with OBJ_INFO_BRUSH instead of OBJ_INFO_SYMBOL, etc.
Object-Creation Statements
The following statements can be used to create new objects. All of the statements may be used to create objects on Layout windows. All of the statements except for Create Frame may be used to create objects on Map windows. Create Arc statement: Creates an arc. Create Ellipse statement: Creates an ellipse or a circle. (A circle is simply a special case of an arcan arc with equal width and height.) Create Frame statement: Creates a frame. Frames are special objects that exist only on Layout windows; each frame can display the contents of an open window. Thus, if you want to place two maps on your page layout, create two frames. Create Line statement: Creates a line. Create Point statement: Creates a point. Create Pline statement: Creates a polyline. Create Rect statement: Creates a rectangle. Create Region statement: Creates a region. Create RoundRect statement: Creates a rounded rectangle.
169 User Guide
MapBasic 10.5
Chapter 9: Graphical Objects Creating New Objects Create Text statement: Creates a text object. AutoLabel statement: This statement labels a Map window by drawing text objects to the Cosmetic layer. This statement does not create labels, it creates text objects. To create labels, use the Set Map statement.
Object-Creation Functions
The following MapBasic functions return object values: CreateCircle( ) function: returns a circle object. CreateLine( ) function: returns a line object. CreatePoint( ) function: returns a point object. CreateText( ) function: returns a text object.
In some ways, object-creation functions are more powerful than the corresponding object-creation statements, because a function call can be embedded within a larger statement. For example, the following Update statement uses the CreateCircle( ) function to create a circle object for every row in the table: Update sites Set obj = CreateCircle(lon, lat, 0.1) This example assumes that the sites table has a lon column containing longitude values (x coordinates) and a lat column containing latitude values (y coordinates).
Chapter 9: Graphical Objects Creating New Objects y As Float End Type Dim objcoord(5) As Point Dim numnodes, i As Integer, myobj As Object numnodes = 3 set CoordSys Earth objcoord(1).x = -89.213 objcoord(1).y = 32.017 objcoord(2).x = -89.204 objcoord(2).y = 32.112 objcoord(3).x = -89.187 objcoord(3).y = 32.096 Create Pline Into Variable myobj 0 For i = 1 to numnodes Alter Object myobj Node Add (objcoord(i).x,objcoord(i).y) Next Insert Into cables (obj) Values (myobj)
MapBasic 10.5
171
User Guide
Chapter 9: Graphical Objects Creating Objects Based On Existing Objects The Insert and Update statements are both powerful, flexible table-manipulation statements. In the preceding examples, the statements operated only on one column (the graphical object column, Obj); however, you can manipulate any column of your table using Insert and Update.
Creating a Buffer
A buffer region is a region representing the area within a certain distance of another object or objects. Buffers are useful for locating objects within a certain distance of other objects. For instance, you can create a buffer around a fiber optic cable to find all the dig sites within three hundred meters of the cable. You can use the Create Object statement to create buffer regions. The following example creates a 300-meter buffer region around the selected segment of cable, then searches for dig locations within the buffer: Dim danger_zone As Object Create Object As Buffer From selection Into Variable danger_zone Width 300 Units "m" Select * From dig_sites Where dig_site.obj Within danger_zone MapBasic also provides a Buffer( ) function, which returns an object value representing a buffer region.
Chapter 9: Graphical Objects Creating Objects Based On Existing Objects The Merge operation is an exclusive-or (XOR) process. If you merge two region objects, and one of the objects is completely contained within the other object, the merge operation removes the smaller objects area from the larger object, leaving a hole. Merge creates a new object. The two merged regions still exist in the source table. You may want to remove the two original regions, as shown below: Select * From Territory Where TerrName = "Western Territory" or TerrName = "NV" Delete From selection Create Object As Union and Create Object As Intersection let you create a region that represents logical combinations of two or more regions. These statements are different from Merge because they work with all of the segments of the source regions, not just the common segments. A Union is the total area of all polygons. An Intersection is the overlapping area. The object created by a union or an intersection may contain new nodes that dont appear in the original regions. MapBasic also provides a Combine( ) function, which returns the object produced by combining two other objects.
Creating Isograms
An Isogram is a map that displays a set of points that satisfy a distance or time condition. Isograms are either IsoChrones or IsoDistances. An IsoChrone is a polygon or set of points representing an area that can be traversed from a starting point in a given amount of time along a given road network. An IsoDistance is a polygon or set of points representing an area that can be traversed from a starting point travelling a given distance along a given road network. Using the Create Object As Isogram statement you can create one or more of these regions, each with a different brush and pen style to differentiate them on your map. In order to create an Isogram, you need the use of an external service such as Envinsa. To create an Isogram: 1. Open a connection to Envinsa using the Open Connection statement. The statement returns a handle to the connection in a variable that is passed on. 2. Configure the Isogram connection with the Set Connection Isogram statement. 3. Create the desired region with the Create Object As Isogram statement.
MapBasic 10.5
Chapter 9: Graphical Objects Modifying Objects SphericalOffsetXY( ) function: returns a copy of initial object by a specified distance and angle. The Distance Type used must be Spherical. CartesianOffset( ) function: returns a copy of initial object by a specified distance and angle. The Distance Type used must be Cartesian. CartesianOffsetXY( ) function: returns a copy of initial object by a specified distance and angle. The Distance Type used must be Cartesian.
Modifying Objects
General Procedure for Modifying an Object
MapBasic provides many statements that you can use to modify an existing map object. Regardless of which statement you use to modify an object, the process of modifying an object is as follows: 1. Make a copy of the original object. (Often, this involves declaring an object variable, issuing a Fetch statement to position the row cursor, and issuing an assignment statement of the form variable_name = tablename.obj). 2. Issue statements or functions to modify the object. (This often involves issuing one or more Alter Object statements.) 3. Issue an Update statement to store the modified object back in the table. The TextBox program demonstrates this process. If the user checks the Change Text Color to Match Box Color check box, the TextBox program uses an Alter Object statement to change the color of the selected object, and then uses an Update statement to store the altered text object back in the table.
Repositioning An Object
Use the Objects Move statement to move objects a specified distance along the positive X axis. You can also specify the Distance Units and Distance Type. Use the Objects Offset statement to make a new copy of objects offset a specified distance along the positive X axis. You can also specify the Distance Units and Distance Type and specify whether the copied objects are placed in the same table as the source objects or into a different table.
MapBasic 10.5
174
User Guide
Chapter 9: Graphical Objects Modifying Objects Include "mapbasic.def" Dim myobj As Object, mysymbol As Symbol mysymbol = CurrentSymbol() Fetch First From selection myobj = selection.obj If ObjectInfo(myobj, OBJ_INFO_TYPE) = OBJ_POINT Then Alter Object myobj Info OBJ_INFO_SYMBOL, mysymbol Update selection Set obj = myobj Where RowID = 1 Else Note "The selected object is not a point." End If To modify the height of a text object that appears on a Layout window, change the objects Font style (by issuing an Alter Object statement with an Info clause). To modify the height of a text object that appears on a Map window, change the objects x- and y-coordinates (by issuing an Alter Object statement with a Geography clause). To modify the height of a map label, issue a Set Map statement.
The Objects Erase statement corresponds to MapInfo Professionals Objects > Erase command, and the Objects Intersect statement corresponds to MapInfo Professionals Objects > Erase Outside command. Both operations operate on the objects that have been designated as the editing target. The editing target may have been set by the user choosing Objects > Set Target, or it may have been set by the MapBasic Set Target statement. For an introduction to the principles of specifying an editing target, see the MapInfo Professional User Guide.
MapBasic 10.5
175
User Guide
Points Of Intersection
As mentioned earlier, you can add nodes to a region or polyline object by issuing an Alter Object statement. However, the Alter Object statement requires that you explicitly specify any nodes to be added. If you want to add nodes at the locations where two objects intersect, use the Objects Overlay statement or the OverlayNodes( ) function. Call the IntersectNodes( ) function to determine the coordinates of the point(s) at which two objects intersect. IntersectNodes( ) returns a polyline object containing a node at each point of intersection. Call ObjectInfo( ) to determine the number of nodes in the polyline. To determine the coordinates of the points of intersection, call ObjectNodeX( ) and ObjectNodeY( ).
Turning Labels On
A MapInfo Professional user can configure labeling options through the Layer Control window. A MapBasic program can accomplish the same results through the Set MapLabel statement. For example, the following statement displays labels for layer 1: Set Map Layer 1 Label Auto On Visibility On
Chapter 9: Graphical Objects Working With Map Labels To modify individual labels through MapBasic, use a Set MapLabel statement that includes one or more Object clauses. For example, the following statement hides two of the labels in a Map window: Set Map Layer 1 Label Object 1 Visibility Off Object 3 Visibility Off For each label you want to customize, include an Object clause. In this example, Object 1 refers to the label for the tables first row, and Object 3 refers to the label for the tables third row. To save custom labels, save a workspace file; see the MapBasic Save Workspace statement. CAUTION: Packing a table can invalidate custom (edited) labels previously stored in workspaces. When you store edited labels by saving a workspace, the labels are represented as Set MapObject statements. Each Object clause refers to a row number in the table. If the table contains rows that have been marked deleted (i.e., rows that appear grayed out in a Browser window), packing the table eliminates the deleted rows, which can change the row numbers of the remaining rows.
In other words, if you pack a table and then load a previously-saved workspace, any edited labels contained in the workspace may be incorrect. Therefore, if you intend to pack a table, you should do so before creating custom labels. If the only deleted rows in the table appear at the very end of the table (i.e., at the bottom of a Browser window), then packing the table will not invalidate labels in workspaces.
Querying Labels
Querying a Map windows labels is a two-step process: 1. Initialize MapBasics internal label pointer by calling LabelFindFirst( ), LabelFindByID( ), or LabelFindNext( ). 2. Call Labelinfo( ) to query the current label. For an example, see Labelinfo( ) in the MapBasic Help, or see the sample program, LABELER.MB.
Chapter 9: Graphical Objects Working With Map Labels 2. Save a workspace file. 3. View the workspace file in a text editor, such as the MapBasic editor. Edits to individual labels are represented as Set Map Layer Label Object statements in the workspace.
Set Map
ObjectInfo( ), ObjectGeography( )
LabelFindByID( ), LabelFindFirst( ), LabelFindNext( ), Labelinfo( ) MapBasic programs cannot select labels. Labels are only stored in workspaces. Not applicable. Labels cannot appear in layouts (except when a map is in a layout). A label's text height is controlled by its font. Zooming in or out does not affect a label's text height. Given a label, the Labelinfo( ) function can return a text object that approximates the label. See LABELER.MBX for an example.
Select
Text objects can be stored in mappable tables. Text objects created in a Layout can be saved in a workspace. Text height is affected by the current map scale. Text grows larger as you zoom in, and smaller as you zoom out. Not applicable. Given a text object, there is no MapBasic function that returns a Label.
When you create a label, you specify the labels anchor point (in x- and y-coordinates). For example, if you are viewing a map of the World table, this statement creates a label that acts as a title: Set Map Layer 1 Label Object 1 Visibility On show this records label Anchor (0, 85) anchor the label at this (x,y) Text "Map of World"set labels text
MapBasic 10.5 178 User Guide
Chapter 9: Graphical Objects Working With Map Labels Position Center set position relative to anchor Font("Arial",289,20,0)set font style (20-point, etc.) The resulting label can act as a map title.
If you need to place text on your map, you may find it easier to create labels, rather than text objects. You could create a table whose sole purpose is to be labeled, using this procedure: 1. Create a table (using the Create Table statement) that contains a character column. Make the character column wide enough to store the text that you want to appear on the map. Make the table mappable (using the Create Map statement). 2. Add the table to your Map window (using the Add Map statement). Use the Set Map statement to set the tables labeling options (font, Auto On, etc.). 3. When you want to add text to the map, insert a point or line object into the table, using an invisible symbol style (shape 31) or invisible pen style (pattern 1). The object will not be visible, but its label will appear. (Use line objects if you want the text to be rotated.) The sample program COGOLine.mb demonstrates how to create a line object at a specific angle.
With this strategy, you do not need to use Set MapObject statements to customize each labels position. You can display labels at their default positions. Then, if you want to move a label, move the object that corresponds to the label.
MapBasic 10.5
179
User Guide
Each MapBasic application has a CoordSys system setting that represents the coordinate system currently in use by that application. The default coordinate system setting is the Earth (longitude, latitude) system. By default, every MapBasic application can work with objects from Earth maps, and most MapInfo tables fall into this category. If a MapBasic application needs to work with objects on a Layout window, you must first issue a Set CoordSys Layout statement, as follows: Set CoordSys Layout Units "in" The Set CoordSys Layout statement lets you specify a paper unit name, such as in (inches). This dictates how MapBasic interprets Layout window coordinate information. To work in centimeters or millimeters, specify the unit name as cm or mm respectively. The following program opens a Layout Window, then places a title on the layout by creating a text object. Since the object is created on a Layout window, the Create Text statement is preceded by a Set CoordSys Layout statement. Include "mapbasic.def" Dim win_num As Integer Layout win_num = FrontWindow() Set CoordSys Layout Units "in" Create Text Into Window win_num "Title Goes Here" (3.0, 0.5) (5.4, 1.0) Font MakeFont("Helvetica", 1, 24, BLUE, WHITE) In the example above, the Layout coordinate system uses inches as the unit of measure. All of the coordinates specified in the Create Text statement represent inches. After you change the coordinate system through the Set CoordSys statement, the new coordinate system remains in effect until you explicitly change it back. Every MapBasic application has its own coordinate system setting. This allows one application to issue a Set CoordSys statement without interfering with any other applications that are running. The MapBasic coordinate system is independent of the coordinate system used by any MapInfo Professional Map window. The default coordinate system is latitude/longitude (NAD 1927) (represented by decimal degrees, not degrees, minutes, and seconds.)
MapBasic 10.5 180 User Guide
Chapter 9: Graphical Objects Coordinates and Units of Measure All coordinates specified in MapBasic statements or functions should be in latitude and longitude unless you change the MapBasic coordinate system with the Set CoordSys statement. For example, the function Centroidx( ) returns the longitude of an objects centroid in decimal degrees, by default, even if the object is stored in a table or a window that has been assigned a different coordinate system. For example, the selection resulting from the statement below has the values: WY -107.554 43, the longitude and latitude of the centroid of Wyoming: Select state, CentroidX(obj), CentroidY(obj) From states Where state = "WY" After the following statements are executed, the selection contains: WY -934612.97 2279518.38; the coordinates reflect an Albers projection. Set CoordSys Earth Projection 9, 62, "m", -96, 23, 29.5, 45.5, 0, 0 Select state, CentroidX(obj), CentroidY(obj) From states Where state = "WY" To reset the MapBasic coordinate system to its default, issue the following statement: Set CoordSys Earth
Units of Measure
MapBasic programs deal with the following units of measure: Area units, such as square miles and acres, represent measurements of geographic areas. For a complete list of the area units supported by MapBasic, see Set Area Units in the MapBasic Reference Guide. Because different area units are supported, functions, such as Area( ), can return results in whatever units are appropriate to your application. Distance units, such as kilometers and miles, represent measurements of geographic distance. For a list of distance units supported by MapBasic, see Set Distance Units in the MapBasic Reference Guide. Paper units, such as inches or centimeters, represent non-geographic distances. For example, if you issue a Set Window statement to reset the width or height of a Map window, you specify the windows new size in paper units, such as inches (on the screen).
At any point during a MapInfo Professional session, there is a current distance unit, a current area unit, and a current paper unit. The default units are miles, square miles, and inches, respectively. The effect of default units is best illustrated by example. The following statement creates a circle object: obj_var = CreateCircle(x, y, 5) Because MapBasics default distance unit is miles, the circle object will have a radius of five miles. However, if you reset the distance unit by issuing a Set Distance Units statement, the meaning of the radius parameter (5) changes. Thus, the following example creates a circle object with a radius of 5 kilometers: Set Distance Units "km" obj_var = CreateCircle(x, y, 5)
MapBasic 10.5
181
User Guide
Chapter 9: Graphical Objects Advanced Geographic Queries To reset the current area unit or the current paper unit, use the Set Area Units statement or the Set Paper Units statement, respectively.
For example, when comparing points with regions: Points are Within regions. Regions Contain points. The following statement selects the state(s) containing a distribution center object:
MapBasic 10.5
182
User Guide
Chapter 9: Graphical Objects Advanced Geographic Queries Select * From states Where obj Contains distribution_ctr The next statement selects all of the landfills within a county: Select * From landfill Where obj Within county_obj The Within operator and the Contains operator test whether the centroid of an object is inside the other object. Use Entire(ly) to test whether the whole object is inside another object. Use Part(ly) to test whether any part of an object is within the other object. The next statement selects all sections of a highway with any part going through a county: Select * From highway Where obj Partly Within countyobj The Partly Within operator tests whether any portion of the first object is within the other object or touching it at any point. You also can use the Entirely Within operator to test if all of an object is within the area of another object. Since checking all of the segments of an object involves more calculations than checking only the centroid, conditions that involve the Partly modifier or the Entirely modifier evaluate more slowly. The Intersects operator can be used with all types of objects. If any part of an object crosses, touches, or is within the other object, the objects intersect. Regions that touch at one corner intersect. A point on a node of a polyline intersects the polyline, lines that cross intersect, and a point inside a region intersects that region. The table below summarizes MapBasics geographic operators: Operator Contains Usage objectA Contains objectB Evaluates TRUE if: first object contains the centroid of the second object first object contains part of the second object first object contains all of the second object first objects centroid is within the second object part of first object is within the second object the first object is entirely inside of the second object the two objects intersect at some point
Contains Part
objectA Contains Part objectB objectA Contains Entire objectB objectA Within objectB
Contains Entire
Within
Partly Within
objectA Partly Within objectB objectA Entirely Within objectB objectA Intersects objectB
Entirely Within
Intersects
MapBasic 10.5
183
User Guide
Chapter 9: Graphical Objects Advanced Geographic Queries If you use a subselect in the Where clause instead of the variable mycounty, you can produce the same results with fewer statements: Select * From doctors Where obj Within (Select obj From counties Where name="Marion" And state="IN") Notice that the subselect (the latter select, which appears in parentheses) returns a table with only one column and one rowthe object representing Marion County, Indiana. MapInfo Professional examines each row in the doctors table to determine whether that row is inside Marion County. The subselect performs the same function as the variable in the previous example (mycounty), because it returns the appropriate object to the expression. To ensure that the subselect returns only the object column, the Select clause of the subselect lists only one column, obj. The statement will not evaluate properly if there are many columns in the subselect or if the column isnt an object column. Use the Any( ) operator when the subselect returns multiple rows. The next example shows a subselect that uses Any( ) to process a group of rows. It finds all the doctors in counties that have a per-capita income of less than $15,000. Compare the locations with each county in the subselect. Select * From doctors Where obj Within Any (Select obj From counties Where inc_pcap < 15000) Switch the order in the Select statement to select counties instead of doctors. The statement below finds all the counties that have a doctor specializing in neurology: Select * From counties Where obj Contains (Select obj From doctors Where specialty = "Neurology") The following example finds all the states bordering Nebraska: Select * From states Where obj Intersects (Select obj From states Where state = "NE")
MapBasic 10.5
185
User Guide
Chapter 9: Graphical Objects Advanced Geographic Queries district information in the projects table to begin with. Determining the district may be the reason to perform the join in the first placeto see which projects are in which congressional districts. The SQL Select statement for that operation is: Select * From projects, congdist Where projects.obj Within congdist.obj After you have joined the tables geographically, you can use the Update statement to enter the congressional district names (from the name column) into the projects table (the column cd) as follows: Update Selection Set cd = name The resulting projects table now contains the name of the congressional district for every project. The following example calculates the total dollars spent on projects in each congressional district: Select congdist.name, sum(project.amt) From congdist, project Where congdist.obj Contains project.obj Group By 1 Since the table order in the Where clause has changed, use the condition Contains instead of Within.
MapBasic 10.5
186
User Guide
10
This chapter discusses how a MapBasic application can take advantage of Windows-specific technology.
Chapter 10: Advanced Features of Microsoft Windows Declaring and Calling Dynamic Link Libraries (DLLs)
MapBasic 10.5
188
User Guide
Chapter 10: Advanced Features of Microsoft Windows Declaring and Calling Dynamic Link Libraries (DLLs)
Passing Parameters
Many DLLs take parameters; for example, the example above shows a Declare statement for a DLL routine that takes two parameters. MapBasic can pass parameters two ways: By value (in which case MapInfo Professional copies the arguments onto the stack), or by reference (in which case MapInfo Professional puts the address of your MapBasic variable on the stack; the DLL then can modify your MapBasic variables). For an introduction to the conceptual differences between passing parameters by reference vs. by value, see MapBasic Fundamentals. To pass a parameter by value, include the ByVal keyword in the Declare statement (as shown in the example above). If you omit the ByVal keyword, the argument is passed by reference. The following MapBasic data types may not be passed by value: Arrays, custom data types (i.e., structures), and aliases. Fixed-length string variables may be passed by value, but only if the DLL treats the parameter as a structure. See String Arguments, below.
MapBasic 10.5
189
User Guide
Chapter 10: Advanced Features of Microsoft Windows Declaring and Calling Dynamic Link Libraries (DLLs)
String Arguments
When calling a DLL routine, a MapBasic program can pass variable-length string variables by reference. If you are writing your own DLL routine in C, and you want MapBasic to pass a string by reference, define the argument as char * from your C program. CAUTION: When MapBasic passes a by-reference string argument, the DLL routine can modify the contents of the string variable. However, DLL routines should not increase the size of a MapBasic string, even if the string is declared as variablelength in MapBasic.
A MapBasic program can pass fixed-length string variables by reference or by value. However, if you pass the argument by value, the DLL routine must interpret the argument as a C structure. For example, if your MapBasic program passes a 20-character string by value, the DLL could receive the argument as a structure consisting of five four-byte Integer values. When a MapBasic program passes a string argument to a DLL, MapInfo Professional automatically includes a null character (ANSI zero) to terminate the string. MapInfo Professional appends the null character regardless of whether the MapBasic string variable is fixed-length or variable-length. If your DLL routine will modify the string argument, make sure that the string is long enough. In other words, take steps within your MapBasic program, so that the string variable that you pass contains a sufficiently long string. For example, if you need a string that is 100 characters long, your MapBasic program could assign a 100-character string to the variable before you call the DLL routine. The MapBasic function String$( ) makes it easy to create a string of a specified length. Or you could declare the MapBasic string variable to be a fixed-length string (for example, Dim stringvar As String * 100 will define a string 100 bytes long). MapBasic automatically pads fixed-length string variables with spaces, if necessary, so that the string length is constant.
Array Arguments
MapBasic allows you to pass entire arrays to DLL routines in the same way that you can pass them to MapBasic sub-procedures. Assuming that a DLL accepts an array as an argument, you can pass a MapBasic array by specifying the array name with empty parentheses.
User-Defined Types
Some DLLs accept custom data types as parameters. (Use the Type statement to create custom variable types.) MapBasic passes the address of the first element, and the rest of the elements of the user-defined type are packed in memory following the first element. CAUTION: For a DLL to work with custom variable types, the DLL must be compiled with structure packing set to tightest packing (one-byte boundaries). For example, using the Microsoft C compiler, you can use the /Zp1 option to specify tightest packing.
Logical Arguments
You cannot pass a MapBasic Logical value to a DLL.
MapBasic 10.5 190 User Guide
Chapter 10: Advanced Features of Microsoft Windows Declaring and Calling Dynamic Link Libraries (DLLs)
Handles
A handle is a unique integer value defined by the operating environment and used to reference objects such as forms and controls. Operating-environment DLLs use handles to Windows (HWND), Device Contexts (hDC), and so on. Handles are simply ID numbers and you should never perform mathematical functions with them. If a DLL routine takes a handle as an argument, your MapBasic program should declare the argument as ByVal Integer. If a DLL function returns a handle as its return value, your MapBasic program must declare the functions return value type as Integer.
MapBasic 10.5
191
User Guide
Chapter 10: Advanced Features of Microsoft Windows Declaring and Calling Dynamic Link Libraries (DLLs) The Declare Function statement establishes a reference to the kernel library. Note that the library is referred to as kernel although the actual name of the file is krnl386.exe. Windows uses the correct library if your program refers to kernel. The kernel library receives special handling because it is a standard part of the Windows API. If you create your own library, your Declare Function statements should reference the actual name of your DLL file. If you use DLLs to store custom ButtonPad icons and/or custom draw cursors, you can use the same basic techniquecalling SystemInfo(SYS_INFO_MIPLATFORM)to determine which DLL to use. However, the MapBasic syntax is somewhat different: Instead of using a Declare statement, you reference DLL resources (bitmap icons and cursors) by including a File clause in the Create ButtonPad statement, as shown in the following example. Declare Sub Main Declare Function getDLLname() As String Declare Sub DoIt Sub Main Dim s_dllname As String s_dllname = getDLLname() Create ButtonPad "Custom" As ToolButton Calling doit Icon 134 File s_dllname Cursor 136 File s_dllname End Sub Function getDLLname() As String If SystemInfo(SYS_INFO_MIPLATFORM) = MIPLATFORM_WIN32 Then getDLLname = "..\icons\Test32.DLL" Else getDLLname = "..\icons\Test16.DLL" End If End Function Sub DoIt this procedure called if the user uses the custom button... End Sub See Creating Custom Button Icons and Draw Cursors on page 193 for a discussion of creating custom ButtonPad icons.
MapBasic 10.5
Chapter 10: Advanced Features of Microsoft Windows Creating Custom Button Icons and Draw Cursors If you are having trouble passing custom MapBasic data types (structures) to your DLL, make sure that your C data structures are packed to one-byte boundaries, as discussed above. MapBasic can pass arguments by reference (the default) or by value. Note, however, that passing arguments by value is not standardized among compilers; for example, different compilers behave differently in the way that they process C-language doubles by value. Therefore, you may find it more predictable to pass arguments by reference. When you pass an argument by reference, you are passing an address; the major compilers on the market are consistent in their handling of addresses. It is good programming to make your DLLs self-contained. In other words, each DLL routine should allocate whatever memory it uses, and it should free whatever memory it allocated. It is important to set up your MapBasic Declare statement correctly, so that it declares the arguments just as the DLL expects the arguments. If a DLL routine expects arguments to be passed by value, but your program attempts to pass the arguments by reference, the routine may fail or return bad data.
MapBasic 10.5
193
User Guide
Chapter 10: Advanced Features of Microsoft Windows Creating Custom Button Icons and Draw Cursors Each of the icons built into MapInfo Professional has a numeric code. For a listing of the codes, see ICONS.DEF. To see an individual buttons code, run ICONDEMO.MBX, and place the mouse cursor over a button; the buttons ToolTip shows you the buttons code. If none of MapInfo Professionals built-in icons are appropriate for your application, you will want to create custom icons, as described in the following pages.
Custom Icons
To create custom icons for MapInfo Professional, you need a resource editor. The MapBasic development environment does not include its own resource editor; however, MapBasic programs can use the resources that you create using third-party resource editors. For example, you could create custom icons using AppStudio (the resource editor that is provided with Microsoft Visual C). On Windows, custom icons are stored in a DLL file. Before you begin creating custom icons, you should develop or acquire a DLL file where you intend to store the icons. This DLL file can be a stub file (i.e., a file that does not yet contain any useful routines). You must create two bitmap resources for each custom icon. The first bitmap resource must be 18 pixels wide by 16 pixels high; this is the icon that will appear if the user does not check the Large Buttons check box in MapInfo Professionals Toolbar Options dialog box. The second bitmap resource must be 26 pixels wide by 24 pixels tall; this is the icon that will appear if the user does check the Large Buttons check box. You must create both resources. The process of creating custom bitmaps involves the following steps: Acquire or develop the DLL file where you will store your custom icons. Edit the DLL using a resource editor, such as AppStudio. For each icon you wish to create, add two bitmap (BMP) resources: one bitmap that is 18 wide by 16 high, and another bitmap that is 26 wide by 24 high (in pixels). You must create bitmap resources, not icon resources. Assign sequential ID numbers to the two bitmap resources. For example, if you assign an ID of 100 to the 18 x 16 bitmap, assign an ID of 101 to the 26 x 24 bitmap. Once you have created the pair of bitmap resources, you can incorporate your custom bitmaps into your MapBasic application using either a Create ButtonPad or an Alter ButtonPad statement. In your program, refer to the ID of the smaller (18 x 16) bitmap resource. For example, if you assigned the IDs 100 and 101 to your bitmap resources, your program should refer to ID 100, as shown in the following statement:
Alter ButtonPad "Tools" Add PushButton Icon 100 File "MBICONS1.DLL" HelpMsg "Add new record" Calling new_route Show The DLL file where you store your custom icons (in this example, MBICONS1.DLL) must be installed on your users system, along with the .MBX file. The DLL file can be installed in any of the following locations:
MapBasic 10.5 194 User Guide
Chapter 10: Advanced Features of Microsoft Windows Inter-Application Communication Using DDE The directory where the .MBX file is located; the directory where the MapInfo Professional software is installed; the users Windows directory; the system directory within the Windows directory; or anywhere along the users search path.
If you place the DLL in any other location, your MapBasic program must specify the directory path explicitly (for example, Icon 100 File "C:\GIS\MBICONS1.DLL"). Note that the ProgramDirectory$( ) and ApplicationDirectory$( ) functions can help you build directory paths relative to the MapInfo Professional directory or relative to the directory path where your MBX is installed.
MapBasic 10.5
195
User Guide
Chapter 10: Advanced Features of Microsoft Windows Inter-Application Communication Using DDE
Refer to the MapBasic Reference Guide or online Help for detailed information on these statements and functions. To initiate a DDE conversation, call the DDEInitiate( ) function. DDEInitiate( ) takes two parameters: an application name, and a topic name. Typically, the application parameter is the name of a potential server application (for example, Excel is the DDE application name of Microsoft Excel). The list of valid topic parameters varies depending of the application. Often, the topic parameter can be the name of a file or document currently in use by the server application. For instance, if Excel is currently editing a worksheet file called TRIAL.XLS, then a MapBasic application can initiate a conversation through the following statements: Dim channelnum As Integer channelnum = DDEInitiate("Excel", "TRIAL.XLS") In this example, Excel is the application name, and TRIAL.XLS is the topic name. Many DDE applications, including MapInfo Professional, support the special topic name System. You can use the topic name System to initiate a conversation, then use that conversation to obtain a list of the available topics. Each DDE conversation is said to take place on a unique channel. The DDEInitiate( ) function returns an integer channel number. This channel number is used in subsequent DDE-related statements. Once a conversation has been initiated, the MapBasic application can send commands to the server application by issuing the DDEExecute statement. For instance, a MapBasic application could instruct the server application to open or close a file.
MapBasic 10.5
196
User Guide
Chapter 10: Advanced Features of Microsoft Windows Inter-Application Communication Using DDE A MapBasic application can request information from the server application by calling the DDERequest$( ) function. When calling DDERequest$( ), you must specify an item name. A DDE item name tells the server application exactly what piece of information to return. If the server application is a spreadsheet, the item name might be a cell name. Use the DDEPoke statement to send information to the server. Generally, when a MapBasic application pokes a value to the server application, the value is stored in the appropriate document, as if it had been entered by the user. The following example shows how a MapBasic program can store the text NorthEast Territory in a cell in the DDE servers worksheet. DDEPoke channelnum, "R1C2", "NorthEast Territory" Once a DDE conversation has completed its task, the MapBasic (client) application should terminate the conversation by issuing a DDETerminate or DDETerminateAll statement. DDETerminate closes one specific DDE conversation; DDETerminateAll closes all open DDE conversations that were opened by that same application. Multiple MapBasic applications can be in use at one time, with each application conducting its own set of DDE conversations. When a MapBasic application acts as a DDE client, the application may generate runtime errors if the server application times-out (does not respond to the clients actions within a certain amount of time). MapInfo Professional stores the time-out setting in the Windows registry For more details about how MapInfo Professional stores settings in the registry, search for registry in the MapBasic online Help index.
MapBasic 10.5
197
User Guide
Chapter 10: Advanced Features of Microsoft Windows Inter-Application Communication Using DDE The following table shows the actions and items supported by a DDE conversation with Application as MapInfo and Topic as System. DDE action Peek request DDE item name SysItems Effect MapInfo Professional returns a TAB-separated list of item names accepted under the System topic. Topics SysItems Formats Version MapInfo Professional returns a TAB-separated list of currently available topics (System, and the names of all running MapBasic applications). MapInfo Professional returns a list of all Clipboard formats supported by MapInfo Professional (TEXT). MapInfo Professional returns a text string representing the MapInfo Professional version number, multiplied by 100. For example, MapInfo Professional 9.5.0 returns 950". See example below. MapInfo Professional interprets the string as a MapBasic expression and returns the value as a string. If expression is invalid, MapInfo Professional returns an error. This functionality applies to MapInfo Professional 4.0 and higher. MapInfo Professional tries to execute the message as a MapBasic statement, as if the user had typed the statement into the MapBasic window. The statement cannot contain calls to user-defined functions, although it can contain calls to standard functions. The statement cannot reference variables that are defined in compiled applications (.MBX files). However, the statement can reference variables that were defined by executing Dim statements into the MapBasic window.
Peek request
Topics
Peek request
Formats
Peek request
Version
Peek request
A MapBasic expression
Execute
A text message
For example, the following MapBasic programwhich you can type directly into the MapBasic windowconducts a simple DDE conversation using MapInfo as the application and System as the topic. Dim i_channel As Integer i_channel = DDEInitiate("MapInfo", "System") Print DDERequest$(i_channel, "Version") DDETerminate i_channel The DDEInitiate( ) function call initiates the DDE conversation. Then the DDERequest$( ) function performs a peek request, using Version as the item name.
MapBasic 10.5
198
User Guide
Chapter 10: Advanced Features of Microsoft Windows Inter-Application Communication Using DDE If you use the name of a running MapBasic application (for example, C:\MB\SCALEBAR.MBX, or SCALEBAR.MBX, or SCALEBAR) as the DDE topic name, you can use any item name from the table below. The following table shows the actions and items supported by a DDE conversation with Application as MapInfo and Topic as the name of a running MapBasic application. DDE action Peek request DDE item name {items} Effect MapInfo Professional returns a TAB-separated list of the global variables defined by the running application. See example below. MapInfo Professional returns a string representing the value of the variable. If the MapBasic application has a function called RemoteQueryHandler( ), MapInfo Professional calls the function. The function can determine the item name by calling CommandInfo(CMD_INFO_MSG). MapInfo Professional stores the new value in the variable. If the MapBasic application has a procedure called RemoteMsgHandler, MapInfo Professional calls the procedure. The procedure can determine the text message by calling CommandInfo(CMD_INFO_MSG).
Peek request
Peek request
Poke
Execute
A text message
For example, the following MapBasic program which you can type directly into the MapBasic window conducts a simple DDE conversation using SCALEBAR.MBX as the topic. This conversation prints a list of the global variables used by SCALEBAR.MBX. This conversation will only work if the application SCALEBAR.MBX is already running. Dim i_channel As Integer i_channel = DDEInitiate("MapInfo", "SCALEBAR.MBX") Print DDERequest$(i_channel, "{items}" ) DDETerminate i_channel
MapBasic 10.5
Chapter 10: Advanced Features of Microsoft Windows Inter-Application Communication Using DDE When a conversation uses the name of a MapBasic application as the topic, and the client sends an execute message, MapInfo Professional calls the applications RemoteMsgHandler procedure, which can then call CommandInfo( ) to determine the text of the execute message.
A MapBasic application can act as the client in one DDE conversation, while acting as the server in another conversation. A MapBasic application can initiate a conversation with another MapBasic application, or with MapInfo Professional itself.
MapBasic 10.5
200
User Guide
Chapter 10: Advanced Features of Microsoft Windows Incorporating Windows Help Into Your Application
MapBasic 10.5
201
User Guide
Integrated Mapping
11
You can control MapInfo Professional using programming languages other than MapBasic. For example, if you know how to program in Visual Basic, you can integrate a MapInfo Professional Map window into your Visual Basic application, while doing mostmaybe even allof your programming in Visual Basic. This type of application development is known as Integrated Mapping, because you are integrating elements of MapInfo Professional into another application. If you already know how to program in other programming languages, such as C or Visual Basic, you will find that Integrated Mapping provides the easiest way to integrate MapInfo Professional windows into non-MapBasic applications. If you are interested in using .Net to create integrated mapping applications, see Integrated Mapping in .Net on page 262.
Chapter 11: Integrated Mapping What Does Integrated Mapping Look Like?
When you integrate a map into your program, the user sees a genuine MapInfo Professional Map windownot a bitmap, metafile, or any other type of snapshot. You can allow the user to interact with the map (for example, using the Zoom tools to magnify the map). An integrated Map window has all of the capabilities of a Map window within MapInfo Professional. When the user runs an Integrated Mapping application, the MapInfo Professional splash screen (the image that ordinarily displays while MapInfo Professional is loading) does not appear.
Chapter 11: Integrated Mapping Technical Overview of Integrated Mapping Your program manipulates MapInfo Professional by constructing strings that represent MapBasic statements, using OLE Automation (or DDE, if you prefer) to send the strings to MapInfo Professional. MapInfo Professional executes the statements as if you had typed the statements into the MapBasic window. If you want to open a Map window, use MapBasics Map From statement, just as you would in a conventional MapBasic program. But in an Integrated Mapping application, you also issue additional statements (for example, Set Next Document Parent) to make the Map window become a child window of your application. This process is known as reparenting the window. You can reparent Map, Browse, Graph, Layout, and Legend windows. Reparenting MapInfo Professionals windows into another application does not give MapInfo Professional access to the other applications data. Before you can display data in a MapInfo Professional window, you must store the data in a MapInfo table. This illustration shows the major elements of an Integrated Mapping application:
Note that the compiled MapBasic program (.MBX) element is optional. For some applications, you might not need to create a compiled MapBasic program. However, if you have already written MapBasic programs, you can continue to use your existing MapBasic code as part of an Integrated Mapping solution.
MapBasic 10.5
204
User Guide
Chapter 11: Integrated Mapping A Short Sample Program: Hello, (Map of) World Your users computer must have enough free memory and system resources to run both your client program and MapInfo Professional simultaneously. Your client program (for example, your Visual Basic program) must be able to act as an OLE Automation controller or as a DDE client. OLE Automation is strongly recommended, because it is faster and more reliable than DDE. Automation also provides better error reporting than DDE. MapInfo Professional uses OLE properties to report runtime error codes; if you use DDE instead of OLE, you cannot retrieve runtime error codes. Your client program must be able to create a user-interface element (for example, a window, form, or control) as a place-holder for where the map will go. Your client program must also be able to determine the Windows HWND value of the user-interface element. For example, in Visual Basic you can place a PictureBox control on a form. When you send a command to MapInfo Professional, telling the application to create a map inside the PictureBox, you must specify the PictureBoxs HWND.
MapBasic 10.5
205
User Guide
Chapter 11: Integrated Mapping A Closer Look at Integrated Mapping mi.do "Create Menu ""MapperShortcut"" ID 17 As ""(-"" " End Sub When you run this Visual Basic program, it launches MapInfo Professional in the background, and creates a Map window. The Map window behaves as a child window of the Visual Basic program. The following sections provide detailed explanations of each step in the Integrated Mapping process.
MapBasic 10.5
206
User Guide
Chapter 11: Integrated Mapping A Closer Look at Integrated Mapping Under Window, multiple instances of MapInfo Professional can be running simultaneously. If you launch MapInfo Professional, and then launch an Integrated Mapping application that calls Visual Basics CreateObject( ) function, two separate instances of MapInfo Professional will be running.
Chapter 11: Integrated Mapping A Closer Look at Integrated Mapping msg = "Set Application Window " & FormName.hWnd mapinfo.Do msg Then, whenever you want to integrate a MapInfo Professional window into the Visual Basic application, send MapInfo Professional a Set Next Document statement, followed by the MapBasic statement that creates the window. For example, the following commands create a MapInfo Professional Map window as a child window of the Visual Basic program. (MapFrame is the name of a PictureBox control in Visual Basic.) msg = "Set Next Document Parent " & MapFrame.hWnd & " Style 1" mapinfo.Do msg msg = "Map From States" mapinfo.Do msg The Set Next Document statement lets you reparent document windows. Within the Set Next Document statement, you specify the HWND (handle) of a control in your Visual Basic program. The next time you create a MapInfo Professional window (using the Map, Graph, Browse, Layout, or Create Legend statements), the newly-created window is reparented, so that it has your client program as its parent. The Set Next Document statement includes a Style clause which controls the type of window you will create. The example above specifies Style 1 which produces a child window with no border. You could specify Style 2 to produce a popup window with a half-height title bar (like MapInfo Professionals Legend window), or Style 3 to produce a popup window with a full-height title bar. For each window that you reparent, issue a pair of statements a Set Next Document Parent statement, followed by the statement that creates the window. After you create the window, you may want to query the value WindowID(0) to obtain MapInfo Professionals Integer Window ID for the new window. (Many MapBasic statements require that you know the windows ID.) mapid = Val(mapinfo.eval("WindowID(0)")) Note that even after you have reparented a Map window, MapInfo Professional maintains that window. If part of the window needs to be repainted, MapInfo Professional automatically repaints it. Therefore, your client program can simply ignore any erase or repaint messages pertaining to the reparented window. If you are working in C, you might not be able to ignore erase messages. In this case you should set your parent windows style to include the WS_CLIPCHILDREN window style.
MapBasic 10.5
208
User Guide
Chapter 11: Integrated Mapping A Closer Look at Integrated Mapping Note that the process for reparenting the Info window is different than the process for reparenting Map windows. When reparenting the Info window, you do not use the Set Next Document statement. The process is different because there is only one Info window, whereas you can have numerous Map windows. Legend windows are a special case. Ordinarily, the MapInfo Professional user interface has only one Legend window, just as it has only one Info window. However, the MapBasic language includes a Create Legend statement, so that you can create additional Legend windows. To reparent MapInfo Professionals standard one and only Legend window, use MapBasics Set Window Legend Parent statement. To create a custom Legend window and reparent it, use MapBasics Set Next Document statement, and then use MapBasics Create Legend statement. Note that in this case, you are creating a Legend that is tied to one specific Map or Graph window. Unlike MapInfo Professionals default Legend window, such custom Legend windows do not change when the active window changes. You can make a legend float inside a Map window. In the Set Next Document statement, specify the Map windows HWND as the parent. The legend becomes a frame trapped within the Map window. For an example of this technique, see the sample program FindZip.
Chapter 11: Integrated Mapping A Closer Look at Integrated Mapping ScaleWidth and ScaleHeight are properties of a Visual Basic form, representing the forms current width and height. The ScaleMode property must be set to Pixels, so that ScaleWidth and ScaleHeight represent pixel measurements.
MapBasic 10.5
210
User Guide
Chapter 11: Integrated Mapping A Closer Look at Integrated Mapping Main Toolbar Buttons Zoom Out Grabber Info HotLink Label Ruler Drag Window Symbol Line Polyline Arc Polygon Ellipse Rectangle RoundedRect Text Frame AddNode Number 1706 1702 1707 1736 1708 1710 1734 1711 1712 1713 1716 1714 1715 1717 1718 1709 1719 1723 Identifier Code M_TOOLS_SHRINK M_TOOLS_RECENTER M_TOOLS_PNT_QUERY M_TOOLS_HOTLINK M_TOOLS_LABELER M_TOOLS_RULER M_TOOLS_DRAGWINDOW M_TOOLS_POINT M_TOOLS_LINE M_TOOLS_POLYLINE M_TOOLS_ARC M_TOOLS_POLYGON M_TOOLS_ELLIPSE M_TOOLS_RECTANGLE M_TOOLS_ROUNDEDRECT M_TOOLS_TEXT M_TOOLS_FRAME M_TOOLS_ADD_NODE
You also can create custom drawing-tool buttons, which call your program after being used. For a general introduction to the capabilities of custom toolbuttons, see Creating the User Interface. For details on using custom toolbuttons within an Integrated Mapping application, see Using Callbacks to Retrieve Info from MapInfo Professional.
Chapter 11: Integrated Mapping A Closer Look at Integrated Mapping To remove one or more items from a MapInfo Professional shortcut menu, use MapBasics Alter MenuRemove statement, or redefine the menu entirely by using a Create Menu statement. For details, see the MapBasic Reference Guide or online Help. To add custom items to a MapInfo Professional shortcut menu, use MapBasics Alter MenuAdd statement, and specify the Calling OLE or Calling DDE syntax; see Using Callbacks to Retrieve Info from MapInfo Professional. To eliminate a shortcut menu entirely, use the MapBasic statement Create Menu to redefine the menu, and use the control code (- as the new menu definition. For example, the following statement destroys MapInfo Professionals shortcut menu for Map windows: mapinfo.do "Create Menu ""MapperShortcut"" ID 17 As ""(-"" "
Chapter 11: Integrated Mapping A Closer Look at Integrated Mapping When you run a MapBasic application (MBX file) via Automation, the MBX will not trap its own runtime errors. You can run an MBX by using the Do method to issue a MapBasic Run Application statement. However, if a MapBasic runtime error occurs within the MBX, the MBX will halt, even if the MBX uses the MapBasic OnError statement. If you are building an MBX which you will call via Automation, try to keep the MBX simple. Within the MBX, avoid using MapBasics OnError statement; instead, do as much error checking and prevention as possible in the controlling application before running the MBX.
MapBasic 10.5
213
User Guide
Chapter 11: Integrated Mapping Using Callbacks to Retrieve Info from MapInfo Professional Note the space after the keyword Interactive. That space is necessary; without the space, the command string would include the substring InteractiveSet which is not valid MapBasic syntax. Because each command string ends with a space, MapInfo Professional can detect that Interactive and Set are separate keywords. If you combine multiple MapBasic statements into a single command string, make sure you include a space after each statement, so that MapInfo Professional can detect that the string contains separate statements.
MapBasic 10.5
214
User Guide
Chapter 11: Integrated Mapping Using Callbacks to Retrieve Info from MapInfo Professional The status bar text changes in MapInfo Professional. MapInfo Professionals status bar does not appear automatically in Integrated Mapping applications. If you want your client program to emulate MapInfo Professionals status bar, you must set up your application so that MapInfo Professional notifies your client program whenever the status bar text changes.
MapBasic 10.5
215
User Guide
Chapter 11: Integrated Mapping Using Callbacks to Retrieve Info from MapInfo Professional 7. If you want MapInfo Professional to notify your client program whenever the user uses a custom menu command, define a custom menu command (for example, using the Alter MenuAdd statement to add an item to one of MapInfo Professionals shortcut menus). Define the custom menu command so that it uses the syntax Calling OLE methodname (using the method name you specified in step 4). 8. Within the method(s) that you defined, issue whatever statements are needed to process the arguments sent by MapInfo Professional. 9. If you created a SetStatusText method, MapInfo Professional sends a simple text string to the method, representing the text that MapInfo Professional would display on the status bar. If you want to emulate MapInfo Professionals status bar, add code to this method to display the text somewhere in your user interface. 10. If you created a WindowContentsChanged method, MapInfo Professional sends a four-byte integer (representing a MapInfo Professional window ID number) to indicate which Map window has changed. Add code to this method to do whatever processing is necessary in response to the windows changing. For example, if you are keeping track of the Map windows current zoom level, you may want to call MapInfo Professionals MapperInfo( ) function to determine the Map windows latest zoom level. 11. If you are using methods to handle custom buttons or menu commands, MapInfo Professional sends a comma-delimited string to your custom method. Within your method, parse the string. The exact format of the string varies, depending on whether the user used a menu command, a point-mode drawing tool, a line-mode drawing tool, etc. Processing the Data Sent to a Callback explains the syntax of the comma-separated string.
MapBasic 10.5
216
User Guide
Chapter 11: Integrated Mapping Using Callbacks to Retrieve Info from MapInfo Professional
Value 1 2 3 4 5 6 7 8
Codes That Have Meaning After a Button Event CMD_INFO_X CMD_INFO_Y CMD_INFO_SHIFT CMD_INFO_CTRL CMD_INFO_X2 CMD_INFO_Y2 CMD_INFO_TOOLBTN
CMD_INFO_MENUITEM
For an explanation of each code, see CommandInfo( ) in the MapBasic Reference Guide or online Help. When you create a custom menu command or button that uses the Calling OLE methodname syntax, MapInfo Professional constructs a string with all eight CommandInfo( ) return values, separated by commas. The string begins with the prefix MI: so that your OLE server can determine that the method call was made by MapInfo Professional. The string that MapInfo Professional sends to your method is constructed in the following manner: "MI:" + CommandInfo(1) CommandInfo(3) CommandInfo(5) CommandInfo(7) + + + + "," "," "," "," + + + + CommandInfo(2) + "," + CommandInfo(4) + "," + CommandInfo(6) + "," + CommandInfo(8)
If you assign a unique ID number to each of your custom buttons, you can have all of your buttons call the same method. Your method can determine which button called it by examining the seventh argument in the comma-separated string. Once MapInfo Professional sends the comma-separated string to your method, it is up to you to add code to your method to parse the string. Suppose your Integrated Mapping application adds a custom menu command to the MapInfo Professional shortcut menu. Every time the user chooses that custom menu command, MapInfo Professional sends your OLE method a comma-separated string. If the custom menu command has an ID number of 101, the string might look like this: "MI:,,,,,,,101" In this case, most of the elements of the comma-separated string are empty, because the CommandInfo( ) function can only return one piece of information about menu events (as is indicated in the table above). Of the eight slots in the string, only slot number eight pertains to menu events.
MapBasic 10.5 217 User Guide
Chapter 11: Integrated Mapping Alternatives to Using OLE Callbacks Now suppose you create a custom MapInfo Professional toolbar button that allows the user to click and drag to draw lines on a map. Every time the user uses that custom drawing tool, MapInfo Professional sends your OLE method a comma-separated string, which might look like this: "MI:-73.5548,42.122,F,F,-72.867702,43.025,202," In this case, the comma-separated string contains several values, because CommandInfo( ) is able to return several pieces of relevant information about toolbutton events. The first two elements indicate the x- and y-coordinates of the location where the user clicked; the next two elements indicate whether the user held the Shift and Ctrl keys while clicking; the next two elements indicate the coordinates of the location where the user released the mouse button; and the last element indicates the buttons ID number. The final slot in the string is empty, because slot number eight pertains to menu events, not button events.
MapBasic 10.5
218
User Guide
DDE Callbacks
When you create custom toolbar buttons or menu commands, you specify a Calling clause. To handle the callback through DDE, use the syntax Calling DDE server, topic. Whenever the user uses the custom button or menu command, MapInfo Professional opens a DDE connection to the DDE server that you designate, and then sends a string to the DDE topic that you designate. The string uses the format discussed in Processing the Data Sent to a Callback on page 216 (for example, MI:101). For an example of a DDE callback, see the sample program FindZip. The Form Load procedure sends MapInfo Professional an Alter ButtonPadAdd statement to create a custom toolbar button. The new toolbutton definition includes the following calling clause: Calling DDE "FindZip", "MainForm" Whenever the user clicks on the map using the custom tool, MapInfo Professional opens a DDE connection to the FindZip application, and then sends a string to the MainForm topic. (MainForm is the value of the forms LinkTopic property.) For an introduction to DDE, see Using the Development Environment.
MBX Callbacks
If you create a compiled MapBasic application (MBX file), then you can set up your custom buttons and menu commands so that they call MapBasic procedures in the MBX. In the Calling clause, use the syntax Calling procedure (where procedure is the name of a procedure in the MapBasic program). After your Visual Basic application launches MapInfo Professional, run your MBX by sending MapInfo Professional a Run Application statement. For example: mapinfo.do "Run Application ""C:\MB\MYAPP.MBX"" " For an introduction to creating custom buttons and menu commands, see Creating the User Interface.
Online Help
An Integrated Mapping application can invoke MapInfo Professional dialog boxes by using MapInfo Professionals RunMenuCommand OLE method. If your application invokes a MapInfo Professional dialog box, you can control whether online help is available for the dialog box.
MapBasic 10.5
219
User Guide
MapBasic 10.5
220
User Guide
Chapter 11: Integrated Mapping Related MapBasic Statements and Functions For example, MapInfo Professionals Find dialog box has the ID number 2202. If you want to provide your own online help for the Find dialog box, set up your help file so that your custom help topic has the Context ID number 2202. Note the following points: MapBasic does not include a HTML help compiler. Microsoft provides this for free at: http://www.microsoft.com/downloads/details.aspx?FamilyID=00535334-C8A6-452F-9AA0D597D16580CC&displaylang=en MapInfo Professionals dialog box ID numbers are likely to change in future versions.
SearchPoint( ), SearchRect( )
SearchInfo( )
Set Map
MapBasic 10.5
221
User Guide
Chapter 11: Integrated Mapping Related MapBasic Statements and Functions Statement/Function Name Set Next Document Description Reparents a document window, such as a Map window, to be a child window of your client program. Controls various aspects of MapInfo Professional windows. Creates or modifies thematic map layers. Some values returned by SystemInfo( ) are specific to Integrated Mapping. Example: Specify SYS_INFO_APPLICATIONWND to retrieve the applications HWND. WindowID( ), WindowInfo( ) Return info about MapInfo Professional windows, even reparented windows.
MapBasic 10.5
222
User Guide
The Application object represents the instance of MapInfo Professional. Each object in the MBApplications collection represents a MapBasic application that is currently running. Each object in the MBGlobals collection represents a global variable defined by one of the running MapBasic applications.
MapBasic 10.5
223
User Guide
Chapter 11: Integrated Mapping OLE Automation Object Models The following chart provides additional objects available in MapInfo Professionals OLE Automation Type Library. Methods and Properties are described in detail on the following pages.
MapBasic 10.5
224
User Guide
Using the OLE Object Model from within the MapInfo Professional Process
The OLE Automation object model was originally designed to be used from a client application running in a separate process (such as, an Integrated Mapping application). However, you can also use the object model to execute commands from a DLL that is called from a running MapBasic program. If you take this approach, there are two things to keep in mind: You need to execute your commands against the MapInfo Professional process into which your DLL is loaded. This means you do NOT obtain the OLE object by executing a "CreateObject" function call, because this would create a second instance of MapInfo Professional. Instead, you need to use the OLE object that represents the current MapInfo Professional process. You obtain this value by calling the MapBasic function SystemInfo with the SYS_INFO_APPIDISPATCH attribute. The function returns an integer value that represents the IDispatch pointer for the primary OLE object. You pass this value from your MapBasic code to your DLL code and convert it into an OLE variable that you can use to call methods like Do and Eval (the exact mechanism for converting the pointer to an OLE object depends on the programming language you use to implement your DLL). If you want to use the callback notifications, be sure to register your callback object using the new RegisterCallback method, and not the older SetCallback. If you use SetCallback you take the risk that some other application running inside of MapInfo Professional will "steal" the callback slot associated with that method. Using RegisterCallback will eliminate this risk.
FullName
Application Parent
Version
ProductLevel
MapBasic 10.5
225
User Guide
LastErrorCode
Eval( string )
RunCommand( string )
RunMenuCommand( menuid )
MapBasic 10.5
226
User Guide
MapInfo Professional-generated notifications. Use this method when you register a callback from within the MapInfo Professional process (for example, from a DLL that is called via MapBasic). Using this method ensures that your callback object will work side-by-side with other applications that may be running within the MapInfo Professional process.
Unregisters an OLE Automation object that was registered
UnregisterCallback (IDispatch)
via the RegisterCallback method. You must pass the same argument that was used in the call to RegisterCallback.
By default, MapInfo Professional will call all valid notification methods. Using this method you can control which callback notifications are sent to the callback object. For example, if your callback object implements WinContentsChanged and the SetStatusText methods, but in certain situations you only want to receive the SetStatusText notifications, you can call SetCallbackEvents ( <dispatch id>, CallbackEvents.WindowChanged ) to tell MapInfo Professional to only send window change notifications. See CallbackEvents below for details.
MapBasic 10.5
227
User Guide
You can use one or more of these flags to SetCallbackEvents. To use more than one of the enumeration values, you must do a "bitwise or" operation. For example, the C++ call to turn the WindowContentsChanges and SetStatusText notification on is SetCallbackEvents( <dispatch id>, (int ) (WindowChanged | SetStatusText) ).
MapBasic 10.5
228
User Guide
int DockSizeCY
BOOL Floating
BOOL Pinned
BSTR Title
MapBasic 10.5
229
User Guide
void Float (left, top, right, bottom) void FloatSize (*left, *top, *right, *bottom)
The DockPosition enumeration is defined with these members: PositionFloat, PositionLeft, PositionTop, PositionRight,
230 User Guide
MapBasic 10.5
You can use these enumeration values in properties and methods of the DockWindow object.
Count
Application
Parent
For example, the following statements determine the name of a running MapBasic application:
MapBasic 10.5
231
User Guide
Chapter 11: Integrated Mapping OLE Automation Object Models Dim appsList As Object Dim firstname As String Set appsList = mapinfo.MBApplications If appsList.Count > 0 Then firstname = appsList(1).Name End If
Eval( string )
Count
Application
Parent
MapBasic 10.5
232
User Guide
Name Type
Application Parent
The following Visual Basic example examines and then alters the value of a global variable (g_status) in a MapBasic application. Dim globinfo As Object Dim old_value As Integer Look at the globals used by the first running MapBasic app: Set globinfo = mapinfo.MBApplications(1).MBGlobals Look at a globals current value by reading its "Value" property: old_value = globinfo("g_status").Value Assign a new value to the global: globinfo("g_status") = old_value + 1 The expression globinfo("g_status") is equivalent to globinfo("g_status").Value because Value is the default property.
MapBasic 10.5
233
User Guide
MBApp
LongLat
SuppressDlgs
Setting the Workspace property is the first step to using the MIMapGen object. MIMapGen is designed to work in situations where there is a single map window (for example, when a web page shows a single map). To begin using MIMapGen, set the Workspace property, so that MapInfo Professional loads a workspacetypically, a workspace that contains a single Map window. Then you will be able to use the other methods and properties to manipulate the Map window.
MapBasic 10.5
234
User Guide
RenderMap( )
ZoomMap (double ZoomFactor) ClickCenterMap (long MouseX, long MouseY) ClickCenterZoomMap (long MouseX, long MouseY, double ZoomFactor) ClearCosmeticLayer( )
Recenters the map based on the mouse click position, and zooms the map based on the zoom factor; negative number zooms out.
Same effect as the Map menu command: Deletes all objects from the Cosmetic layer. Same effect as the Query menu command: De-selects all rows. Performs a radius search.
SQLUnselectAll( ) SearchRadius (double CenterPointX, double CenterPointY, double Radius) SearchRadiusExt (double CenterPointX, double CenterPointY, double OuterPointX, double OuterPointY) SearchPoint (double CenterPointX, double CenterPointY) SearchRect (double x1, double y1, double x2, double y2)
Performs a radius search, To define the search circle, specify the center point and a point that is somewhere along the circles radius.
MapBasic 10.5
235
User Guide
Updates CenterX, CenterY, Zoom, ImageHeight, and ImageWidth. Converts screen coordinates (pixels) into map coordinates (for example, longitude/latitude).
Calls the MapBasic sub procedure RemoteMapGenHandler in the MBX application that was executed through the MBApp property. Use this method to run MapBasic statements in an MBX file.
The searching methods search only the topmost selectable layer. To access the search results, see the MISearchInfo object.
Fields
TableName
MapBasic 10.5
236
User Guide
Chapter 11: Integrated Mapping OLE Automation Object Models To obtain an MISearchInfo object, use one of the MIMapGen objects search methods: SearchRadius, SearchRadiusExt, SearchPoint, or SearchRect.
To obtain a collection of MIRow objects, reference the Rows property of the MISearchInfo object or the MISelection object.
MapBasic 10.5
237
User Guide
Short: The width of the field; applies to DT_CHAR and DT_DECIMAL fields only. Short: The number of decimal places in a DT_DECIMAL field.
DecimalPlaces
To obtain a collection of MIField objects, reference the Fields property of the MISearchInfo object or the MISelection object.
Fields
TableName
To access the MISelection object, use the GetTable method from the MIMapGen object.
MapBasic 10.5
238
User Guide
-server
-automation or -embedding
-regserver
-unregserver
-helpdiag
The forward slash (/) can be used instead of the minus sign.
MapBasic 10.5
239
User Guide
Getting Started with Integrated Mapping and Visual C++ with MFC
The remainder of this chapter will walk you through the creation of an Integrated Mapping application using Microsoft Visual C++ with MFC. These instructions are written primarily for users of the 32-bit Visual C++ (version 2.0 or higher), but they have also been tested with the 16-bit version of Visual C++ (version 1.52). Differences are noted where appropriate.
MapBasic 10.5
240
User Guide
Chapter 11: Integrated Mapping MapInfo Professional Command-Line Arguments After all of the other #includes add: #include "MapInfow.h" Just below the declaration CprojectnameApp theApp, add the following variable declaration: DMapInfo mapinfo; Near the end of CprojectnameApp::InitInstance, but before the OnFileNew( ) call, add: mapinfo.CreateDispatch("MapInfo.Application");
Open the file MAPINFOW.H and add the following lines at the bottom of the file: extern DMapInfo mapinfo; #include "path-to-mapbasic-directory\mapbasic.h"
Chapter 11: Integrated Mapping MapInfo Professional Command-Line Arguments In MainFrm.CPP, function CMainFrame::OnCreate, we need to do the following: After all of the other #includes add: #include "MapInfow.h" At the end of CMainFrame::OnCreate, add: char str[256]; sprintf(str, "Set Application Window %lu", (long)(UINT)m_hWnd); mapinfo.Do(str);
Demonstrate that this works by adding the following statement to the CprojectnameApp::InitInstance function, just after the OnFileNew( ) call. This will cause MapInfo Professional to display one of its standard dialog boxes within the context of your application: mapinfo.Do("Note \"Hello from MapInfo\""); Please test your application at this point to ensure that it is working properly.
MapBasic 10.5
242
User Guide
Chapter 11: Integrated Mapping Adding Toolbar Buttons and Handlers sprintf(str, "WindowInfo(0, %u)", WIN_INFO_WND); m_windowhwnd = (HWND)atol(mapinfo.Eval(str)); In the OnDestroy method, add the following code before the call to CView::OnDestroy: if (m_windowhwnd) { ::DestroyWindow(m_windowhwnd); m_windowhwnd = NULL; m_windowid = 0L; } In the OnSize method, add the following code after the call to CView::OnSize: if (m_windowhwnd && cx > 0 && cy > 0) { ::MoveWindow(m_windowhwnd, 0, 0, cx, cy, TRUE); }
Chapter 11: Integrated Mapping Adding Toolbar Buttons and Handlers 1. First, follow the instructions listed above (Adding a Map Menu Command on page 243) and create a new menu named Tools, with four new items (Selector, Grabber, Zoom-In, Zoom-Out). Define the UPDATE_COMMAND_UI and COMMAND functions as before, using the appropriate codes from the MAPBASIC.H file for each tool (M_TOOLS_SELECTOR, M_TOOLS_RECENTER, M_TOOLS_EXPAND, and M_TOOLS_SHRINK, respectively). Compile and test your application when youre done. 2. Open the project RC file, select the bitmap resource IDR_MAINFRAME, and make the bitmap 64 pixels wider (room for 4 more 16-pixel buttons). Move the images of the last several buttons to the right, making room just after the paste button. Draw appropriate images for the four new tools, for example, an arrow (selector), a hand (grabber), a magnifying glass (zoom-in), and a magnifying class with a minus sign (zoom-out). 3. Open the String resource, add new strings for each of the new tools. Use the same IDs as you used when creating the menu items earlier; the strings should be a descriptive string followed by \n and the tooltip text. For example, ID_TOOLS_SELECTOR as Select map objects\nSelector; ID_TOOLS_GRABBER as Recenter the map\nGrabber; ID_TOOLS_ZOOMIN as Zoom-In to show less area, more detail\nZoom-In; and ID_TOOLS_ZOOMOUT as Zoom-Out to show more area, less detail\nZoom-Out. 4. In MAINFRM.CPP locate the static UINT BASED_CODE buttons[ ] array and insert the ID constants into the array in the same position that they appear in the bitmap resource. 5. In order to get the user interface right, we need to keep track of which tool is currently selected. In the CprojectnameView header file, add an integer variable to keep track of this: int m_eMouseMode; 6. Initialize this variable in the class constructor, to represent the initial state of the map. Note that well use the MapInfo Professional constants for the various tools to keep track of which one is selected. m_eMouseMode = M_TOOLS_SELECTOR; 7. If you created the menu items first, you already have COMMAND and UPDATE_COMMAND_UI entries in the message map; if not, you should add them now. 8. Update the user interface by calling CCmdUI::SetRadio in each OnUpdate routine, and set the m_eMouseMode variable accordingly in each OnToolsToolname handler. That is, your routines should now read as follows: void CprojectnameView::OnToolsSelector() { m_eMouseMode = M_TOOLS_SELECTOR; mapinfo.RunMenuCommand(M_TOOLS_SELECTOR); } void CprojectnameView::OnToolsGrabber() { m_eMouseMode = M_TOOLS_RECENTER; mapinfo.RunMenuCommand(M_TOOLS_RECENTER); } void CprojectnameView::OnToolsZoomin() { m_eMouseMode = M_TOOLS_EXPAND;
MapBasic 10.5
244
User Guide
Chapter 11: Integrated Mapping Adding Toolbar Buttons and Handlers mapinfo.RunMenuCommand(M_TOOLS_EXPAND); } void CprojectnameView::OnToolsZoomout() { m_eMouseMode = M_TOOLS_SHRINK; mapinfo.RunMenuCommand(M_TOOLS_SHRINK); } void CprojectnameView::OnUpdateToolsSelector(CCmdUI* pCmdUI) { pCmdUI->SetRadio(m_eMouseMode == M_TOOLS_SELECTOR); pCmdUI->Enable(m_windowid); } void CprojectnameView::OnUpdateToolsGrabber(CCmdUI* pCmdUI) { pCmdUI->SetRadio(m_eMouseMode == M_TOOLS_RECENTER); pCmdUI->Enable(m_windowid); } void CprojectnameView::OnUpdateToolsZoomin(CCmdUI* pCmdUI) { pCmdUI->SetRadio(m_eMouseMode == M_TOOLS_EXPAND); pCmdUI->Enable(m_windowid); } void CprojectnameView::OnUpdateToolsZoomout(CCmdUI* pCmdUI) { pCmdUI->SetRadio(m_eMouseMode == M_TOOLS_SHRINK); pCmdUI->Enable(m_windowid); }
Chapter 11: Integrated Mapping Adding Toolbar Buttons and Handlers static BYTE BASED_CODE parms[] = VTS_BSTR; try { InvokeHelper(0x6001000b, DISPATCH_METHOD, VT_EMPTY, NULL, parms, command); } catch(COleDispatchException *e) { // Handle the exception in a manner appropriate to your // application. The error code is in e->m_wCode. AfxMessageBox(e->m_strDescription); e->Delete(); } catch(COleException *e) { AfxMessageBox("Fatal OLE Exception!"); e->Delete(); } }
MapBasic 10.5
246
User Guide
Chapter 11: Integrated Mapping Learning More for MapInfo Professional callbacks once. In an MDI application, documents and their views are destroyed when closed. If you set the IDispatch pointer to a document, it will no longer be valid when the document is closed.
Learning More
To learn more about Integrated Mapping, look at the sample programs provided with the MapBasic development environment. The following samples are provided: Samples\VB\FindZip: Visual Basic program, used as an example throughout this chapter. Samples\VB\VMapTool: Visual Basic program that demonstrates advanced tasks, such as callbacks; requires Visual Basic 4.0 Professional Edition or later. Samples\MFC\FindZip: A sample MFC application. Samples\PwrBldr\Capitals: A sample 16-bit PowerBuilder application. You must have the PowerBuilder runtime environment on your system to run it. Samples\Delphi\TabEdMap: A sample Delphi application.
Check the Samples directory (within the MapBasic directory) for additional samples.
MapBasic 10.5
247
User Guide
12
MapBasic programs can call functions and subroutines written using Microsoft's .Net development platform. You can write code in languages such as C# (Csharp) and VB.Net (Visual Basic for .Net), using Microsoft's Visual Studio development environment. Then you can call those .Net routines from your MapBasic programs. Some tasks that are difficultor, in some cases, not supported at allin the MapBasic language are relatively easy to do in .Net. For example, MapBasic's Dialog statement cannot create dialog boxes with Tab controls or TreeView controls, but you can easily create such dialogs in .Net. You may find it useful to write some parts of your application using .Net, and then call those routines from your MapBasic application.
Chapter 12: Working with .Net Introduction and Requirements for .Net Programmability
Terminology
In this chapter, the term method refers to any sub or function routine written in .Net. For example, a Sub routine written in VB is one type of method, while a Function written in VB is another type of method. Both types of methods can be called from MapBasic. Some methods can be called without first creating an instance of the class. C# programmers refer to these methods as static methods, while VB.Net syntax refers to them as shared functions. In this chapter, we will use the term static method to refer to a method that can be called without first creating an instance of the class.
Getting Started
This section provides a simple example of how to create a class in .Net, and use the class from MapBasic. Calling a .Net method from MapBasic involves six basic steps: 1. Create a class in .Net, containing one or more static methods 2. Build the .Net class into an assembly 3. Make the assembly available to the MapBasic application 4. Add a Declare Method statement to the .MB program 5. Call the method that you declared in the Declare Method statement 6. Compile and run your MapBasic application.
MapBasic 10.5
249
User Guide
MapBasic 10.5
250
User Guide
Chapter 12: Working with .Net Getting Started The SayHello method uses the .Net MessageBox class to display a dialog box such as this:
Since this sample uses the MessageBox class, the project depends on a standard assembly, System.Windows.Forms. If you type in this example yourself, you may need to add a Reference to the System.Windows.Forms assembly to your Visual Studio project.
Chapter 12: Working with .Net Getting Started In this example, we will call the method by its actual name, "SayHello". (You could refer to the method with an alias, using the Alias clause; but for this simple example, it is not necessary to use an Alias. You only need to use the Alias clause when you need to differentiate multiple functions that have the same name.) The Class clause specifies the class name as "MapBasicMethods.Demo" because our source code specified that "MapBasicMethods" is the namespace, and "Demo" is the class name. The Lib clause specifies the name of the assembly file as "MBMethods.dll"; your assembly name will depend on your project settings in Visual Studio. The argument list matches the argument list of the .Net method: one by-value String argument. The return type matches the return type of the .Net method. The MapBasic "Integer" type is a 4-byte integer, which is equivalent to the C# "int" type (also known as System.Int32). Once your Declare Method statement is in place, you can call your .Net method just as you would call any other MapBasic function. For example: ' MapBasic syntax for calling a .Net method Dim i As Integer i = SayHello("Fred") If your .Net method does not have a return value (i.e. it is a Sub rather than a Function, or it is a C# void method), or if you simply want to ignore the return value, omit the final "As" clause from the Declare Method statement. For example: ' MapBasic syntax for declaring a .Net method as a sub Declare Method SayHello Class "MapBasicMethods.Demo" Lib "MBMethods.dll" (ByVal strName As String) Declare Sub Main Sub Main Call SayHello("Fred") End Sub Compile and run the MapBasic program. When your .MBX calls the SayHello method, your .Net assembly is loaded and your static method is called. Note that if your Declare Method statement contains errors (such as misspelling the Class name), your MapBasic program may still compile, but the method call will fail when you try to run your .MBX. Your assembly name, class name, method name and method argument list are not validated until you actually call the method at run-time.
Chapter 12: Working with .Net Getting Started Method keyword -- to be a unique name (i.e. a function name that is not already in use). In the following example, we call a .Net method that is defined with the name ShowDialog, but within the .MB source code, we call the method by the name ShowPointDialog: Declare Method ShowPointDialog Class "MyProduct.MyWrapper" Lib "MyAssembly.DLL" Alias ShowDialog Dim i As Integer i = ShowPointDialog()
() As Integer
Boolean
bool
n/a
n/a
Arguments can be array types. For example, if your .Net method takes an argument that is an array of Integer values, the Declare Method statement might look like this: Declare Method ProcessIntegerArray Class "MyProduct.MyWrapper" Lib "MyAssemblyName" (idNumbers() As Integer) Arguments can be passed by-reference or by-value. The syntax for specifying by-ref vs. by-val varies from language to language. The following table demonstrates how you might pass String arguments by-val vs. by-ref in various cases. You cannot resize a MapBasic array variable within your .Net method.
MapBasic 10.5
253
User Guide
By-Reference Syntax str As String ByRef str As String ref String str
By-Value Syntax ByVal str As String ByVal str As String String str
MapBasic can only pass array arguments and structure arguments ByRef.
Performance Notes
The speed of calling a .Net method depends on how much data you pass via the argument list. The more data you pass as arguments, the longer the call will take. If you find that the execution speed of calling .Net methods is not satisfactory, try to minimize the amount of data that you pass via the argument list.
Chapter 12: Working with .Net Working with Structures in .Net idnum As Integer descript As String area As Float End Type Declare Method ShowParcelDialog Class "MapBasicMethods.Demo" Lib "MBMethods.dll" (p As ParcelInfo) Declare Sub Main Sub Main Dim p As ParcelInfo p.idnum = 23 p.descript = "Sample parcel" p.area = 123.45 Call ShowParcelDialog( p ) End Sub In this example we are passing a ParcelInfo data structure to a .Net method. The next question is: how should the .Net method be written, so that it will be able to receive the data sent from MapBasic? When a .Net method needs to receive structure information sent from MapBasic, you need to do the following: 1. Define a Class in .Net. 2. Give your Class a public constructor, and give this constructor an argument list that matches the fields in your MapBasic structure. For example, if your MapBasic structure contains an integer, a string, and a floating-point number, then your constructors argument list must also take an integer, a string, and a floating-point number. (Your class can also have other constructors, but MapInfo Professional/MapBasic will ignore those other constructors.) 3. Somewhere in one of your .Net classes, write a public static method (the method that you will call from MapBasic). Add an argument to this method, and define the argument type as the Class you created in step 1. The following C# code sample demonstrates how to create a Parcel class that corresponds to the ParcelInfo structure described above: public class { private private private Parcel int m_ID; string m_Description; double m_Area;
public Parcel(int idnum, string description, double area) { m_ID = idnum; m_Description = description; m_Area = area; }
MapBasic 10.5 255 User Guide
Chapter 12: Working with .Net Working with Structures in .Net // TODO: You will probably find it useful to create a Property // for the ID, and for the Description, and for the Area. // MapInfo/MapBasic do not require that Properties exist. } Having defined the Parcel class, you can now define a public static method that takes an argument of type Parcel. public static int ShowParcelDialog(Parcel parc) { // Here you would write code to display the // parcel information in a dialog box... MessageBox.Show("Hello, world"); return 0; } Now your MapBasic program can pass a ParcelInfo structure to the ShowParcelDialog method. While your MapBasic program sends a structure to the method call, the ShowParcelDialog method receives an object of the appropriate type; MapInfo Professional converts the structure to the appropriate .Net type, so that the method call can be performed. (This is why you are required to put a public constructor on your .Net class MapInfo Professional needs the public constructor so that it can convert the MapBasic data structure into an appropriate type of .Net object.) When you pass a MapBasic structure to your .Net method, the call succeeds only if the arguments .Net class has a public constructor with arguments that match the fields in the MapBasic structure. If no such constructor exists, your MapBasic program will produce a run-time error when it attempts to call the method. Note that this is a run-time error condition; the MapBasic compiler cannot detect this type of problem at compile-time. In some cases, you might not start out with an existing MapBasic Type structure as your given instead, you might start out with a pre-existing .Net method signature. Suppose you want to call a .Net method that has already been written, and this existing method expects one argument: a System.Drawing.Point object. public static void ShowPointDialog(System.Drawing.Point p) { MessageBox.Show("p.x is: " + p.X + ", p.y is: " + p.Y); } This methods argument does not match any of the standard MapBasic variable types, such as Integer or String. Therefore, if you want to call this method from MapBasic, you will need to define a MapBasic structure that approximates the .Net argument type (System.Drawing.Point, in this case). The following MapBasic example shows the appropriate syntax: Type Location ix as Integer iy as Integer End Type Declare Method ShowPointDialog Class "MyProduct.MyWrapper" Lib "MyAssembly.DLL" (pnt As Location) . . .
MapBasic 10.5 256 User Guide
Dim loc As Location loc.ix = 23 loc.iy = 42 Call ShowPointDialog(loc) In this example, MapInfo Professional will try to convert the MapBasic structure into a .Net System.Drawing.Point object, by calling a public constructor on the Point class. This conversion process is similar to what happened in the previous example, with one important difference: In this case, you did not have to write the .Net Point class, because it already exists it is a class provided by Microsoft. Because the MapBasic Location structure contains two Integer fields, MapInfo Professional will try to find a public constructor on the Point class that takes two integers. The fields from the MapBasic structure are passed to the .Net constructor, thus creating a .Net Point object. The Point object is passed to the method to complete the call. Some .Net classes do not have public constructors. For example, the System.Drawing.Color structure does not have public constructors; therefore, it is impossible to define a MapBasic structure that approximates a System.Drawing.Color object. If you need to pass color information to your .Net method, give your method separate red, green, and blue arguments. Then, inside your .Net method you can combine those values to form a .Net Color. Public Shared Sub ShowColorDialog(ByRef r As Integer, ByRef g As Integer, ByRef b As Integer) Dim c As Color Dim dlg As ColorDialog dlg = New ColorDialog dlg.Color = Color.FromArgb(r, g, b) If (dlg.ShowDialog = DialogResult.OK) Then c = dlg.Color r = c.R g = c.G b = c.B End If End Sub In this example we are instantiating objects, such as the ColorDialog, and calling non-static methods on those objects. As stated earlier, MapBasic programs (.MB source code) can only call static methods; however, the .Net code that you write inside your static method has no such restriction. Inside your static method, your .Net code can instantiate objects, and use those objects to call nonstatic methods (instance methods).
Chapter 12: Working with .Net Exception Handling to call. In this situation your MapBasic program will produce a run-time error when you attempt to call the .Net method. The simplest way to resolve this type of ambiguity is to use a unique method name for any .Net method to which you will be passing a structure. If you pass a structure to a .Net method, and the .Net method modifies the object passed to it, the corresponding MapBasic structure is not modified. If you need to have your.Net method update your MapBasic argument variables, use ByRef scalar variable arguments (such as ix As Integer) rather than structures.
Exception Handling
An unhandled exception in a .Net method will cause a runtime error in your MapBasic application (MapBasic error code 1666). Any unhandled runtime error in a MapBasic application will halt the .MBX; therefore, you will want to handle all such errors. You can choose whether you prefer to trap your error conditions in your .Net code, or in your .MB code. The .Net error handling mechanism (try-catch-finally blocks) is more robust than the error handling provided in MapBasic. Therefore, it is generally preferable to catch exceptions in your .Net code, rather than allowing exceptions to propagate to your .MB program. However, if you do not want to or for some reason cannot catch an exception in your .Net method, you can handle the resulting runtime error in your .MB program, using MapBasic's OnError statement. The following code demonstrates the MapBasic error-trapping syntax: Sub MakeExternalCall OnError Goto caughtit Call DoSomething() g_status = 0 Exit Sub caughtit:
' Code only comes here if method call caused an error. if Err() = 1666 Then ' Code comes here if we called the .net method, ' but the .net method threw an unhandled exception. ' TODO: Look at Error$() to determine exact exception g_status = -1 else ' Other Err codes might indicate that the method was ' not called, possibly due to a typo in Declare Method Note "Check Declare Method statement. Error: " + Error$() g_status = -2 end if End Sub
MapBasic 10.5
258
User Guide
' Display a .Net MessageBox dialog box with both a message and a caption: Call Show("Table update is complete.", "Tool name") ' Call the .Net Move method to move a file Call Move("C:\work\pending\entries.txt", "C:\work\finished\entries.txt")
MapBasic 10.5
259
User Guide
Chapter 12: Working with .Net Controlling MapInfo Professional from Within a .Net Method
MapBasic 10.5
260
User Guide
Chapter 12: Working with .Net Controlling MapInfo Professional from Within a .Net Method Before you can use the MapInfo.MiPro.Interop.InteropServices class, your .Net project must include a reference to the miadm.dll assembly. . The assembly is located in the MapInfo Professional install directory. If you encounter any errors while building the Named Views sample project, you may need to re-create the miadm.dll reference in the Visual Studio project, so that it specifies the current location for the assembly. The MapInfoApplication class is a wrapper class, which gives .Net programmers easy access to MapInfo Professional's COM interface. This class is provided as a convenience, so that you may access methods, properties and events through a standard .Net class, instead of dealing with the COM interface directly. In addition to providing the Do and Eval methods shown above, the MapInfoApplication class also provides the properties and events listed below.
MapInfoApplication members
Methods Do Executes a MapBasic statement, as if you had typed the statement into the MapBasic window Eval Evaluates a MapBasic expression, and returns the result, as a string Properties FullName Gets the full path to the application executable LastErrorCode Gets an integer representing the last MapBasic error that occurred during a Do or Eval method call LastErrorMessage Gets the error message associated with LastErrorCode Name Gets the application name Version Gets the version number string, representing the version number, multiplied by 100 Events MenuItemClick Occurs when the user selects a custom menu item defined with the syntax: Calling OLE "MenuItemHandler" StatusBarTextChanged Occurs when the MapInfo Professional status bar text changes
MapBasic 10.5
261
User Guide
Chapter 12: Working with .Net Integrated Mapping in .Net WindowContentsChanged Occurs when the contents of the map window change (such as when a map is zoomed in or out)
Chapter 12: Working with .Net Integrated Mapping in .Net 4. Map From -- this statement creates a Map window. The sample application demonstrates the use of these statements; for examples, search the MapForm class for calls to the Do method.
Callback Methods
In some cases, integrated mapping applications need to provide callback methods. If your application needs to execute code whenever certain events occur -- for example, if you need to execute code whenever the user alters the map -- then you will need to set up a callback method, so that MapInfo Professional can call your callback method every time that event occurs. MapInfo Professional will call the following callback methods: The WindowContentsChanged method is called by MapInfo Professional whenever the contents of the map window change (e.g. when a layer is added or removed) The SetStatusText method is called by MapInfo Professional whenever anything happens that would alter the text on the MapInfo Professional status bar. Any custom OLE menu item has a handler method; the name of the handler method is specified in the client application. The sample application defines one custom OLE menu item and specifies MenuItemHandler as the handler name. This method name also appears in the MapBasic statement that defines the custom menu item (the Create Menu statement or the Alter Menu...Add statement).
In the sample application, these callbacks are represented by the IMapInfoCallback interface. The C# version of the interface, from MapInfoCallback.cs, looks like this: public interface IMapInfoCallback { // Method called by MapInfo Professional when window changes int WindowContentsChanged(UInt32 windowID); // Method called by MapInfo Professional when the status bar text changes int SetStatusText(string message); // Method called by MapInfo Professional when user chooses custom OLE menuitem void MenuItemHandler(string commandInfo); } The Visual Basic version of the interface, from MapInfoCallback.vb, looks like this: Public Interface IMapInfoCallback ' Method called by MapInfo Professional when window changes Function WindowContentsChanged(ByVal windowID As UInt32) As Integer ' Method called by MapInfo Professional when the status bar text changes Function SetStatusText(ByVal message As String) As Integer ' Method called by MapInfo Professional when user chooses custom OLE menuitem
MapBasic 10.5 263 User Guide
Chapter 12: Working with .Net Integrated Mapping in .Net Sub MenuItemHandler(ByVal commandInfo As String) End Interface The same source code module contains the MapInfoCallback class, which demonstrates how to implement the IMapInfoCallback interface. Note that the MapInfoCallback class has attributes to mark the class as COM-visible, so that MapInfo Professional will be able to call the methods. The C# syntax for the class attributes: [ClassInterface(ClassInterfaceType.None)] [ComVisible(true)] public class MapInfoCallBack : IMapInfoCallback The VB version of the class attributes: <ClassInterface(ClassInterfaceType.None)> _ <ComVisible(True)> _ Public Class MapInfoCallBack Implements IMapInfoCallback In the same file where the IMapInfoCallback interface is defined, there is a second interface, ICallbackNotify. Implement this interface in your Windows Forms application. In the sample application, this interface is implemented in MapForm.cs or MapForm.vb. Events can cause MapInfo Professional to call the callback (IMapInfoCallback) class, which in turn notifies the client (ICallbackNotify) class. For a better understanding of how and when the various interface methods are called, consider the following sequence of events: 1. The user runs the Integrated Mapping client application, which silently launches MapInfo Professional. In the sample application, this happens in the MapForm.InitializeComObject method. This method launches MapInfo Professional, instantiates the callback object, and registers the callback object with MapInfo Professional: private void InitializeComObject() { // Create the MapInfo Professional object _mapInfoApp = new MapInfoApplication(); // Set parent window for MapInfo Professional dialogs _mapInfoApp.Do("Set Application Window " + this.Handle); // Create the callback object _callbackObject = new MapInfoCallBack(this); // Register the callback object with Professional _mapInfoApp.RegisterCallback(_callbackObject); } 2. The client application calls the MapInfoApplication.Do method to open tables and map windows. In the sample application, this happens in the MapForm.NewMap method, which is called when the user has chosen File > Open to open one or more .tab files. 3. The user modifies the map in some way. In the sample application, the user can select Layer Control from the map window's right-click menu, then use the dialog box to modify the map. MapInfo Professional manages the Layer Control window.
MapBasic 10.5
264
User Guide
Chapter 12: Working with .Net Integrated Mapping in .Net 4. Because the map has been modified, MapInfo Professional notifies the client app by calling the MapInfoCallback.WindowContentsChanged method. 5. The WindowContentsChanged method calls the MapForm.OnWindowContentsChanged method. The code to be included in this method will depend on the purpose of the application. For example, if your application displays information about the map, on the status bar or elsewhere in your form, then you might want to update your form in the OnWindowContentsChanged method. 6. If the application includes a custom OLE menu item, MapInfo Professional calls the menu item's handler method whenever the user selects the menu item. In the sample application, the Alter Menu statement adds an item to the map's context menu, and specifies "MenuItemHandler" as the handler name. Therefore, if the user selects the custom menu item, MapInfo Professional calls the MenuItemHandler method, which then calls the MapForm.OnMenuItemClick method. The code to be included in the OnMenuItemClick method will depend on the purpose of the custom menu item. 7. Whenever the user does something that would cause MapInfo Professional to modify the text on the status bar -- for example, clicking in the map to make a selection -- MapInfo Professional calls the MapInfoCallback.SetStatusText method. This method calls the MapForm.OnStatusBarTextChanged method. If you want to make your client application's status bar look like the MapInfo Professional status bar, you could add code to the OnStatusBarTextChanged method to update your status bar. 8. On exit, we un-register the callback object. In the sample application, this happens in the FormClosed method. private void Form1_FormClosed(object sender, FormClosedEventArgs e) { // Unregister the callback object MapInfoApp.UnregisterCallback(_callbackObject); } The sample application defines one custom OLE menu item. If your application defines multiple OLE menu items, you can have each menu item call its own designated handler method. Or, you can have all of your OLE menu items call the same handler method -- but, if you do, then you will need to give each custom menu item an ID number (by including the ID clause in the Create Menu or Alter Menu...Add statement) so that the handler method can determine which menu item the user selected. Note that the MapInfoCallback class is re-usable. You could write several different integrated mapping applications, and use the same MapInfoCallback class with each of those applications.
MapBasic 10.5
265
User Guide
Chapter 12: Working with .Net Integrated Mapping in .Net It is likely that callback methods will execute on a different thread than the thread that created your user interface. Therefore, your callback methods must detect and correct any thread safety issues before executing any code that affects your user interface. The Windows Forms Control class provides an InvokeRequired property. If InvokeRequired is true, it indicates that the current thread is not the correct thread for updating the Control, in which case, you must use the Control.Invoke method to apply any changes to the Control. The Invoke method ensures that the change is applied on the appropriate thread. For example, the sample MapInfoCallback.SetStatusText method contains the following code, which ensures that any changes made to the status bar occur on the appropriate thread: if (_callbackClient.InvokeRequired) { _callbackClient.Invoke(this._onStatusBarTextChangedDelegate, new Object[] { text }); } else { _callbackClient.OnStatusBarTextChanged(text); } Note that we are using the _callbackClient object (an object that implements ICallbackNotify) to access the InvokeRequired property and the Invoke method. In the sample application, the Form class serves as the ICallbackNotify object: public partial class MapForm : Form, ICallbackNotify In the sample application, the _callbackClient member is a reference to the MapForm. Since the Form class derives from Control, we are able to call _callbackClient.Invoke. Do not perform the callback un-register operation in a destructor method, as that method will probably be called from an incorrect thread.
MapBasic 10.5
266
User Guide
Sample Programs
The MapBasic software includes the following sample program files. Additional examples may have been added after the printing of this manual.
Samples\Delphi Directory
tabmap: run MapInfo Professional as an OLE server using Delphi.
Samples\DLLEXAMP Directory
Samples\DLLEXAMP\Loadlib Directory
loadlib: The files in this directory are the source code to a C language DLL that can be compiled for either Win16 or Win32, and a test program written in MapBasic that exercises the function in the DLL.
Samples\DLLEXAMP\ResDLL Directory
Contains sample programs to demonstrate techniques for Win16 & Win32 compatibility.
Samples\DotNet Directory
Samples\DotNet\HelloWorld Directory
Simple example of calling a .Net method from MapBasic (C# and VB.Net versions)
Samples\DotNet\IntegratedMapping Directory
Integrated Mapping client application written in .Net (C# and VB.Net versions)
Samples\DotNet\NamedViews Directory
Named Views MapBasic tool, which uses .Net for managing XML files and dialog boxes (C# and VB.Net versions). The Named Views application lets you define named views, which act as bookmarks that let you return to that map view at a later time.
Samples\MapBasic Directory
The Samples\MapBasic\ directory contains subdirectories that include sample program files. The contents of each subdirectory is described in the following sections.
Samples\MapBasic\Animator Directory
Animator.mb: demonstrates how Animation Layers can speed up the redrawing of Map windows.
Samples\MapBasic\Appinfo Directory
AppInfo.mb: retrieves information about the MapBasic applications that are currently running.
MapBasic 10.5 268 User Guide
Samples\MapBasic\Autolbl Directory
AutoLbl.mb: labels a map by placing text objects in the Cosmetic layer (emulating the way earlier versions of MapInfo Professional created labels).
Samples\MapBasic\Cogoline Directory
COGOLine.mb: draws a line at a specified length and angle.
Samples\MapBasic\Coordinateextractor Directory
Coordinateextractor.mb: updates two columns with the x and y coordinates in the tables native projection or a user selected projection for each object in the table.
Samples\MapBasic\Csb Directory
CoordSysBounds.mb: enables you to check and set the coordinate system bounds of any mappable MapInfo base table.
Samples\MapBasic\Database Directory
Autoref.mb: refreshes linked tables every (Interval) seconds BuildSQL.mb: allows you to connect to DBMS databases; build, save, and load queries; run queries and preview or download the results. Connect.mb: provides the MapInfo DBMS Connection Connection Manager dialog box and related functions. The connection manager allows you to select an existing connection to use, disconnect existing connections, and get new connections. DescTab.mb: provides a dataLink utility function that given a table opens a dialog box that describes it. DLSUtil.mb: returns the list value at the selection index for Dialog Box List control processing. GetMITab.mb: MapInfo Professional table picker dialog box. MIODbCat.mb: This is the DBMS Catalog tool that is loaded from the MapInfo Professional Tool Manager. This allows the database administrator to create a MapInfo Professional User with the with a MAPINFO_MAPCATALOG table. It also allows the DBA to delete a table from the catalog. MIRowCnt.mb: This is the DBMS Count Rows in Table tool that is loaded from the MapInfo Professional Tool Manager. This tool lets you connect to DBMS databases and run a count(*) against tables, updating the mapcatalog with the results. MISetMBR.mb: This is the CoordSysBounds tool that is loaded from the MapInfo Professional Tool Manager. This tool allows the DBA to change the bounds of a table in the MapInfo_MAPCATALOG table. MIUpldDB.mb: This tool provides the ability to generate the Database specific SQL statements allowing you to upload a MapInfo table.
MapBasic 10.5
269
User Guide
Chapter A: Sample Programs Samples\MapBasic Directory MIUpLoad.mb: This is the Spatialize SQL Server Table tool that is loaded from the MapInfo Professional Tool Manager. This tool provides the ability to upload a MapInfo table to a remote database with spatial column information. The Spatial columns are used with DBMS linked tables, which allows a remote database table to be mappable in MapInfo Professional. PickCol.mb: This tool provides a server table column picker dialog box. PickSel.mb: This tool provides a selection picker dialog box as part of the BuildSQL.mbx. PickTab.mb: This tool provides functions to get a list of server database tables, and table owners (schemas), and contains a generic function that provides a table selection dialog box. PrepSQL.mb: This tool provides a SQL Query prepare function that processes query parameters. The parameters are bound here (resolved and replaced with a value). SQLPVW.mb: This tool resolves each parameter to a value and return the resolved SQL query string given an SQL query string with embedded parameters of a specific format. SQLUtil.mb: This tool provides many utility functions that enable Mapinfo to access to ODBC data. SQLView.mb: This tool provides a SQL DataLink application for testing the SERVER_COLUMNINFO function for all options (except VALUE).
Samples\MapBasic\Disperse Directory
disperse.mb: This tool provides a takes points at given coordinates and disperses them either randomly or systematically.
Samples\MapBasic\DistanceCalc
The Distance Calculator tool (DistanceCalc.MBX) can be used to calculate the distance from a selected object (or group of objects) to the closest or farthest object(s). You can also specify criteria to limit the results.
Samples\MapBasic\DMSCnvrt Directory
DMSCnvrt.mb: This tool converts between columns of Degree/Minute/Second coordinates and columns of decimal-degree coordinates.
Samples\MapBasic\Geoset Directory
Geoset.mb: This tool enables you to create a MapX or MapXtreme Geoset from the layers and settings of a MapInfo Professional Map window, or to read a MapX or MapXtreme Geoset files to load the corresponding tables and layer settings to a MapInfo Professional Map window.
Samples\MapBasic\GridMakr Directory
GridMakr.mb: This tool creates a grid (graticule) of longitude/latitude lines.
Samples\MapBasic\HTMLImageMap Directory
HTMLImageMap.mb: This tool creates a clickable HTML image map from a MapInfo Professional Map window for use in a web browser.
MapBasic 10.5 270 User Guide
Samples\MapBasic\IconDemo Directory
IconDemo.mb: This tool demonstrates the built-in ButtonPad icons provided in MapInfo Professional.
Samples\MapBasic\Inc Directory
inc: This directory contains include files that can be useful when programming in the MapBasic environment. Among these files are: Definition (.DEF) files used by various of the MapBasic tools installed with MapInfo Professional. AUTO_LIB.DEF and RESSTRNG.DEF are needed by the Tool Manager registration system and the tools string localization module, respectively (both of these are stored in the \LIB directory.) MAPBASIC.DEF contains, among other things, the definitions for general purpose macros, logical constants, angle conversion, colors, and string length. These are used as inputs for various MapBasic functions. MENU.DEF contains the definitions needed to access and/or modify MapInfo Professional's dialog boxes, toolbars, and menu items. MAPBASIC.H is the C++ version of MAPBASIC.DEF plus MENU.DEF. MAPBASIC.BAS is the Visual Basic 6.0 version of MAPBASIC.DEF plus MENU.DEF.
Samples\MapBasic\Labeler Directory
labeler.mb: This tool allows you to transfer your layers labels into permanent text objects, label the current selection, and use a label tool and individually label objects into permanent text objects.
Samples\MapBasic\Legends Directory
Legends.mb: This tool allows you to manage two or more Legend windows in MapInfo Professional. (The standard MapInfo Professional user interface has only one Legend window.)
Samples\MapBasic\Lib Directory
lib: This directory contains a library of functions and subroutines that can be useful when programming in the MapBasic environment. In particular, two of these files are used by many of the MapBasic tools installed with MapInfo Professional: AUTO_LIB.MB is used by most tools to help register themselves into the Tools directory. RESSTRNG.MB is used by the localized tools to look up the appropriate language strings in the tools .STR files.
Samples\MapBasic\Linesnap Directory
linesnap.mb: This tool allows you to trim or extend a single-segment line to its intersection point with another chosen line.
Samples\MapBasic\Mapwiz Directory
mapwiz.mb: This tool provides a template which can be used to create a Tool Manager application.
MapBasic 10.5 271 User Guide
Samples\MapBasic\NorthArrow Directory
northarrow.mb: This MapBasic program creates North Arrows.
Samples\MapBasic\Packager Directory
packager.mb: This tool packages a copy of a workspace into a single directory for easier backups, compression, or transfer between computers.
Samples\MapBasic\Regvector Directory
regvector.mb: This tool allows you to copy a table of vector objects (regions, polylines, points, etc.) from one location to another by specifying target locations for three points in the original table.
Samples\MapBasic\RingBuffer Directory
ringbuf.mb: this tool allows you to create multiple donut ring buffers. It also will calculate sums and averages of underlying data within each ring.
Samples\MapBasic\RMW Directory
rotatemapwindow.mb: This tool enables you to rotate the contents of the current map window a specific number of degrees.
Samples\MapBasic\RotateLabels Directory
rotatelabels.mb: This tool allows you to rotate labels.
Samples\MapBasic\RotateSymbols Directory
rotatesymbols.mb: This tool allows you to rotate symbols in a table.
Samples\MapBasic\SeamMgr Directory
seammgr.mb: This tool creates and manages seamless map tables.
Samples\MapBasic\Send2mxm Directory
send2mxm.mb: This tool allows you to write custom MapX Geoset and associated .tab files to create a user-defined subset of a map window's background data for display on a mobile device.
Samples\MapBasic\Shields Directory
Shields.mb: This tool draws decorative frames around text objects. Note that this application only works with true text objects, not map labels.
MapBasic 10.5
272
User Guide
Samples\MapBasic\Snippets Directory
The Snippets directory contains sample programs and code snippets that you can incorporate into your custom MapInfo applications. In addition to containing sample code snippets, this directory also contains three tools that are installed with MapInfo Professional Tool Manager. These are the Named Views tool [NVIEWS.MBX], the Overview tool [OVERVIEW.MBX] and the Scalebar drawing tool [SCALEBAR.MBX]. acad.mb: uses DDE to communicate with AutoCAD for Windows. addnodes.mb: This snippet adds nodes to objects. This can be useful if you intend to project a map; the added nodes prevent slivers from appearing between regions in situations where a large region has a long, straight edge. geocode.mb: This snippet demonstrates how to geocode through MapBasic. geoscan.mb: This snippet scans a table to predict a geocoding hit-rate. get_tab.mb: This is a module, not a complete application. get_tab contains routines to display a dialog box that presents the user with a list of open tables. For an example of using the get_tab routines, see the OverView application. nviews.mb: This snippet creates a named views application that lets you enter a name to describe your current view of a map (current center point and zoom distance). Once a view is defined, you can return to that view by double-clicking it from the Named Views dialog box. To link this application, use the project file nvproj.mbp. objinfo.mb: This snippet displays descriptive information about an object. overview.mb: This snippet opens a second Map window to show an overview of the area in an existing Map window. As you zoom in or out or otherwise change your view in the original map, the overview window adjusts automatically. To link this application, use the project file obproj.mbp. scalebar.mb: This snippet draws a distance scale bar on a map window. To link this application, use the project file sbproj.mbp. textbox.mb: This is the sample program used as an example throughout this manual. To link this application, use the project file tbproj.mbp. watcher.mb: uses DDE to communicate with Microsoft Excel; sets up an Excel worksheet to monitor global variables in a MapBasic application.
Samples\MapBasic\Srchrepl Directory
Srchrepl: performs search-and-replace operations within a table.
MapBasic 10.5 273 User Guide
Samples\MapBasic\SWSpatialize Directory
sw_spatialize: This program allows an existing SQL Server table that has not been set up for spatial data to be spatialized. When a SQL Server table is spatialized, it can have spatial data inserted into and extracted from it.
Samples\MapBasic\Symbol Directory
symbol: allows you to create/edit/delete MapInfo symbols. Editor that lets you customize the MapInfo 3.0 symbol set.
Samples\MapBasic\SyncWindows Directory
syncwindows: This program synchronizes mapper windows, creates objects in all mapper windows, tiles windows, and clears cosmetic layter in all map windows.
Samples\MapBasic\Tablemgr Directory
tablemgr: This application lists all open tables in a list box and provides more information about a table as the user clicks on it. Also allows the user to set some table properties and view table metadata.
Samples\MapBasic\Template Directory
toolapp.mb: This is a template for a MapInfo Professional tool application. To link this application, use the project file toolapp.mbp
Samples\MapBasic\Winmgr Directory
winmgr: This program allows you to set the title of a document window title and set the default view for a table.
Samples\MFC Directory
FindZip: This application demonstrates how Integrated Mapping allows you to integrate elements of MapInfo Professional into a C++ program written using Microsoft Foundation Class (MFC). mdimfc: An Integrated Mapping application using C++.
Samples\PwrBldr Directory
Capitals: An Integrated Mapping application using PowerBuilder. The PowerBuilder runtime libraries are not provided; you must already have PowerBuilder libraries installed to run this application.
MapBasic 10.5
274
User Guide
Samples\VB4 Directory
Callback: OLE automation callbacks. FindZip: This application demonstrates how Integrated Mapping allows you to integrate elements of MapInfo Professional, such as a Map window, into a Visual Basic program. Requires Visual Basic 3.0 or later. VMapTool: A demonstration of advanced Integrated Mapping tasks, such as callbacks. Requires Visual Basic 4.0 Professional Edition or later.
Samples\VB6 Directory
Callback: OLE automation callbacks. FindZip: This application demonstrates how Integrated Mapping allows you to integrate elements of MapInfo Professional, such as a Map window, into a Visual Basic program. Requires Visual Basic 3.0 or later. VMapTool: A demonstration of advanced Integrated Mapping tasks, such as callbacks. Requires Visual Basic 4.0 Professional Edition or later.
MapBasic 10.5
275
User Guide
Summary of Operators
Operators act on one or more values to produce a result. Operators can be classified by the data types they use and the type result they produce.
Numeric Operators
The following numeric operators act on two numeric values, producing a numeric result. Operator + * / \ Mod ^ addition subtraction multiplication division integer divide (drop remainder) remainder from integer division exponentiation Performs a + b a - b a * b a / b a \ b a Mod b a ^ b Example
Two of these operators are also used in other contexts. The plus sign (+) acting on a pair of strings concatenates them into a new string value. The minus sign () acting on a single number is a negation operator, producing a numeric result. The ampersand also performs string concatenation. Operator + & Performs numeric negation string concatenation string concatenation - a a + b a & b Example
Comparison Operators
The comparison operators compare two items of the same general type to produce a logical value of TRUE or FALSE. Although you cannot directly compare numeric data with non-numeric data (for example, String expressions), a comparison expression can compare Integer, SmallInt, and Float data types. Comparison operators are often used in conditional expressions, such as IfThen. Operator = <> <
MapBasic 10.5
Chapter B: Summary of Operators Logical Operators Operator > <= >= Returns TRUE if: a is greater than b a is less than or equal to b a is greater than or equal to b a > b a <= b a >= b Example
Logical Operators
The logical operators operate on logical values to produce a logical result of TRUE or FALSE: Operator And Or Not Returns TRUE if: both operands are TRUE either operand is TRUE the operand is FALSE Example a And b a Or b Not a
Geographic Operators
The geographic operators act on objects to produce a logical result of TRUE or FALSE: Operator Contains Returns TRUE if: first object contains the centroid of the second Example objectA Contains objectB
first object contains part of the second object objectA Contains Part objectB first object contains all of the second object first objects centroid is within the second object part of the first object is within the second object objectA Contains Entire objectB objectA Within objectB
Partly Within
MapBasic 10.5
278
User Guide
Chapter B: Summary of Operators Geographic Operators Operator Entirely Within Intersects Returns TRUE if: the first object is entirely inside the second the two objects intersect at some point Example objectA Entirely Within objectB objectA Intersects objectB
Precedence
A special type of operators are parentheses, which enclose expressions within expressions. Proper use of parentheses can alter the order of processing in an expression, altering the default precedence. The table below identifies the precedence of MapBasic operators. Operators which appear on a single row have equal precedence. Operators of higher priority are processed first. Operators of the same precedence are evaluated left to right in the expression (with the exception of exponentiation, which is evaluated right to left). Priority (Highest Priority) parenthesis exponentiation negation multiplication, division, Mod, integer division addition, subtraction geographic operators comparison operators, Like operator Not And (Lowest Priority) Or MapBasic Operator
For example, the expression 3 + 4 * 2 produces a result of 11 (multiplication is performed before addition). The altered expression (3 + 4) * 2 produces 14 (parentheses cause the addition to be performed first). When in doubt, use parentheses.
MapBasic 10.5
279
User Guide
MapBasic 10.5
280
User Guide
These are the ODBC data types that MapInfo Professional supports: SQL_BIT SQL_TINYINT SQL_SMALLINT SQL_INTEGER: SQL_REAL SQL_BIGINT SQL_DECIMAL SQL_DOUBLE SQL_FLOAT SQL_NUMERIC SQL_BINARY SQL_LONGVARBINARY SQL_VARBINARY SQL_LONGVARCHAR SQL_DATE SQL_TYPE_DATE SQL_TIMESTAMP SQL_TYPE_TIMESTAMP SQL_TIME SQL_TYPE_TIME SQL_CHAR SQL_VARCHAR
Chapter D: Making a Remote Table Mappable Prerequisites for Storing/Retrieving Spatial Data
Chapter D: Making a Remote Table Mappable Creating a MapInfo Map Catalog SYMBOL Char(254), XCOLUMNNAME Char(32), YCOLUMNNAME Char(32), RENDITIONTYPE integer RENDITIONCOLUMN Char(32) RENDITIONTABLE Char(32) It is important that the structure of the table is exactly like this statement. The only substitution that can be made is for the databases that support varchar or text data types. These data types can be substituted for the Char datatype. 4. Create a unique index on the TABLENAME and the OWNERNAME, so only one table for each owner can be made mappable. 5. Grant Select, Update, and Insert privileges on the MAPINFO_MAPCATALOG. This allows the tables to be made mappable by users. The delete privilege should be reserved for database administrators.
MapBasic 10.5
284
User Guide
Chapter E: Data Setting and Management Upgrading Applications from Versions Prior to 6.5
Traditionally these files have been kept in the Windows directory or the Program directory. The strategy for Mapinfo Professional, versions 6.5 or higher, is to install application data files in a peruser location, and search for them in other areas as well allows support for sharing application data files between MapInfo versions and products. By relocating mapinfow.prj a user can share one custom projection files between different versions of Mapinfo Professional. The following files remain in the Program directory: Filename mapinfow.abb mapinfow.prj mapinfow.mnu Abbreviation file Projection file Menu file Description
Keep in Mind:
The installer never asks the user where they want to place application data files. The installer always runs the same way, whether the user has Mapinfo Professional installed or not. There is not an upgrade install for versions 6.5 and higher (for example, you cannot install Mapinfo Professional 10.0 into the same directory as version 9.5, or the installer throws an error).
286 User Guide
MapBasic 10.5
Chapter E: Data Setting and Management Upgrading Applications from Versions Prior to 6.5 Application developers can move or copy files where they want, but Mapinfo Professional searches for them only in these locations and in this order: appdata_dir local_appdata_dir pref_dir program_dir
Pref_dir
Mapinfo Professional writes out mapinfow.prf and mapinfow.wor by default. Version 6.0: Windows directory Versions 6.5 and higher: user profile root\Application Data\MapInfo\MapInfo. If this directory does not exist at startup, then Mapinfo Professional creates it.
home_dir
Windows directory
program_dir
In Version 6.0, MapInfo Professional expects to find many of the appdata files in this location. Version 6.0: location of mapinfow.exe Versions 6.5 and higher: location of mapinfow.exe
appdata_dir
This is a per-user directory introduced in version 6.5. Many of the appdata files are installed in this location. Version 6.0: n/a Versions 6.5 and higher: user profile root\Application Data\MapInfo\MapInfo\Professional\nnn. where nnn is the three-digit version number for MapInfo Professional (for example, 850). If this directory does not exist at start up, MapInfo Professional does not create it. Developers must not assume this represents a valid path.
MapBasic 10.5
287
User Guide
Chapter E: Data Setting and Management Application Data Files and Directories
local_appdata_dir
This is also a per user directory, similar to appdata_dir, except files here do not roam. Version 6.0: n/a Versions 6.5 and higher: user profile root\Local Settings\Application Data\MapInfo\MapInfo\Professional\nnn. where nnn is the three-digit version number for MapInfo Professional (for example, 850). If this directory does not exist at start up, MapInfo Professional does not create it. Developers must not assume this represents a valid path.
common_appdata_dir
This directory is shared by all users on a machine. By default users have read access to everything, permission to create files and write access to files they create. File in this directory do not roam. Support for this directory was added in version 7.0. Versions 6.5 and 6.0: n/a Versions 7.0 or higher: user profile root\All Users\Application Data\MapInfo\MapInfo\Professional\nnn. where nnn is the three-digit version number for MapInfo Professional (for example, 850).
mydocs_dir
Refers to the My Documents directory of the current user. Version 6.0: n/a Versions 6.5 and higher: My Documents
search_for_file
This function locates appdata files. It searches directories for them in the following pre-defined order: Version 6.0: pref_dir, home_dir, program_dir Version 6.5: appdata_dir, local_appdata_dir, pref_dir, program_dir Versions 7.0 or higher: appdata_dir, local_appdata_dir, pref_dir, common_appdata_dir, program_dir
MapBasic 10.5
288
User Guide
Chapter E: Data Setting and Management Application Data Files and Directories
mapinfow.prf
Version 6.0: Uses search_for_file. Regardless of where the files were read from, always writes out to pref_dir. Versions 6.5 and higher: Uses search_for_file. If found, then reads the file and remembers the location. On exit, if file was found at start up and if the user has write access to it, then write it out to that location. Otherwise, write the file to pref_dir.
mapinfow.wor
Version 6.0: Looks in pref_dir, then home_dir. Loads the first one it finds. Versions 6.5 and higher6.5: Uses search_for_file. If found, reads the file and remembers the location. On exit, if file was found at start up, and if the user has write access to it, then write it out to that location. Otherwise, write the file to pref_dir.
startup.wor
Version 6.0: Loaded in order from the following directories: program_dir, pref_dir. Versions 6.5 and higher: Loaded in order from the following directories: pref_dir, appdata_dir, local_appdata_dir, pref_dir, program_dir. Unlike other appdata files, each startup.wor that is found is processed.
mapinfow.clr
Version 6.0: Uses search_for_file. If not found, then displays a dialog box for user to find. If user chooses to save custom defined colors, a new color file is written to pref_dir (or overwrites an existing one). Versions 6.5 and higher: Uses search_for_file. If not found, then displays a dialog box for user to find. If user chooses to save custom defined colors and the color file was located in a per-user directory, then MapInfo Professional updates the existing file. If the color file was read from the program directory, or if the user does not have write access to the file, then MapInfo Professional writes the file to the pref_dir.
mapinfow.pen
Version 6.0: Uses search_for_file. If not found, then displays a dialog box for user to find. Versions 6.5 and higher: Uses search_for_file. If not found, then displays a dialog box for user to find.
mapinfow.fnt
Version 6.0: Uses search_for_file. If not found, then displays a dialog box for user to find. Versions 6.5 and higher: Uses search_for_file. If not found, then displays a dialog box for user to find.
custsymb directory
Version 6.0: Assumes it is under the program_dir. Versions 6.5 and higher: Looks for symbol dir by using search_for_file. If not found, then assumes it is under the program_dir.
289 User Guide
MapBasic 10.5
thmtmplt directory
Version 6.0: If the template dir is specified in the preference file exists, then use it. Otherwise, try to create a template dir under the program_dir. If it cannot be created under program_dir, no template dir is set. In all cases, including the last, MapInfo Professional updates the preference file path. Versions 6.5 and higher: If the template dir specified in the preference file exists, then use it. Otherwise, look for the template dir using search_for_file. If found, then use it. Otherwise, try creating template dir off appdata_dir, then program_dir. Otherwise, no template dir is set. In any case, MapInfo Professional does not set the preference file path.
graphsupport directory
Version 6.0: Use the directory specified in the preference file regardless of whether it exists. If the specified directory is invalid, then the user gets an error message when trying to create a new graph. Versions 6.5 and higher: If the template dir specified in the preference file exists, then use it. Otherwise, look for the graph support dir using search_for_file. If found, then use it. If not, then assume it is off the program_dir, and the user will get error message when trying to create a graph). In versions 7.0 and higher the search_for_file routine includes common_appdata_dir.
Path Tables Workspaces MapBasic Programs Import Files SQL Queries Theme Templates
Versions 6.5 and 6.0 mydocs_dir mydocs_dir program_dir\Tools mydocs_dir mydocs_dir appdata_dir\thmtmplt if exists, program_dir\thmtmplt otherwise mydocs_dir
Saved Queries
MapBasic 10.5
290
User Guide
Chapter E: Data Setting and Management Registry Changes Versions 7.0 or higher default mydocs_dir mydocs_dir uses search_for_file then program_dir if that fails mydocs_dir
Versions 6.5 and 6.0 mydocs_dir mydocs_dir local_appdata_dir if exists, program_dir otherwise mydocs_dir
Registry Changes
MapInfo Professional's use of the registry must be organized to allow each user to work with their own data. The following changes were made to support this organization: The Tool Manager entries are now installed under HKEY_CURRENT_USER. The graph engine now stores custom colors and number formats under HKEY_CURRENT_USER.
MapBasic 10.5
291
User Guide
Chapter E: Data Setting and Management Installer Requirements and Group Policies Filename thmtmplt graphsupport
*
nnn is the three-digit version number for MapInfo Professional (for example, 850).
Filename mapinfow.clr mapinfow.pen mapinfow.fnt mapinfow.abb mapinfow.prj mapinfow.mnu custsymb thmtmplt graphsupport
*
nnn is the three-digit version number for MapInfo Professional (for example, 850).
In version 9.5, we introduced Workgroup installations to MapInfo Professional which allows a System Administrator to set a shared location for users to access Application Data Files. This change may affect some of the default directory settings for these files. The following MapBasic functions help with file locations: GetFolderPath$( ) function Returns the path of a special MapInfo Professional or Windows directory. LocateFile$( ) function Return the path to one of MapInfo Professional's application data files.
MapBasic 10.5
292
User Guide
MapBasic Glossary
If you do not find the term you are looking for in this glossary, check the glossary in the MapInfo Professional User Guide on the MapInfo Professional DVD.
Terms
Term Aggregate functions Definition Functions such as Sum( ) and Count( ), which calculate summary information about groups of rows in a table. See Select in the MapBasic Reference Guide or online Help. A name by which a MapInfo Professional user (or a MapBasic program) refers to an open table. For example, if a table name is C:\MapInfo\Parcels.Tab, the tables alias would be Parcels. Table aliases may not contain spaces; any spaces in a table name become underscore characters in a table alias. Alias is also a MapBasic data type; an alias variable can store a string expression that represents a column name (for example, World.Population). The maximum length of an alias is 32 characters. A special floating layer added to a map that allows for redraw of objects in that layer only. Modifying an object in the animation layer does not cause other layers to redraw. A set of configuration, template, and custom symbol files and directories that affect the basic settings and customizations of maps. These files are stored locally but can be shared remotely by users to achieve a consistent look for their maps. Also known as a parameter. Part of a statement or a function call. If a statement or function requires one or more arguments, you must specify an appropriate expression for each required argument. The argument that you specify is passed to the statement or function. In syntax diagrams in the MapBasic Reference Guide and online Help, arguments are formatted in italics. A grouping of variables of the same type used to keep similar elements together. OLE Automation is technology through which one Windows application can control another Windows application. For example, a Visual Basic application can control MapInfo Professional through MapInfo Professionals Automation methods and properties. See Integrated Mapping. A graph representing values from the users table. Bar charts can be used in the graph window or can be displayed thematically on the map. A debugging aid. To make your program halt at a specific line, place a breakpoint before that line. To place a breakpoint in a MapBasic program, insert a Stop statement and recompile.
294 User Guide
Alias
Animation Layer
Argument
Array
Bar Chart
Breakpoint
MapBasic 10.5
Chapter F: MapBasic Glossary Terms Term Brush Style Definition An objects fill pattern. The style is comprised of pattern, foreground color, and background color. Another word for toolbar. Two different ways of passing parameters to a function or procedure. When you pass an argument by reference (the default), you must specify a variable name when you make the function call; the called function can modify the variable that you specify. When you pass an argument by value (using the ByVal keyword), you do not need to specify a variable name. An application that uses or receives information from another program. Often referred to in database connections or DDE connections. Part of a table or database. A table contains one or more columns, each of which represents an information category (for example, name, address, phone number, etc.). Columns are sometimes referred to as fields. Tables based on raster images do not have columns. A programmers note included in the program. The note has no use in the syntax necessary for compiling the program. In the MapBasic language, an apostrophe (single quotation mark ) marks the beginning of a comment. When an apostrophe appears in a statement, MapBasic ignores the remainder of the line (unless the apostrophe appears inside of a literal string expression). A program that takes the text of a program, checks for syntax errors, and converts the code to an executable format. A component of a dialog box, such as a button or a check box. A set of parameters that specifies how to interpret the locational coordinates of objects. Coordinate systems may be earth (for example, coordinates in degrees longitude/latitude) or non-earth (for example, coordinates in feet) based; earth maps are referenced to locations on the Earth. A temporary layer that exists on every map window. This layer always occupies the topmost position on the layer control. MapInfo Professionals Find command places symbols in the Cosmetic layer to mark where a location was found. The mouse cursor is a small image that moves as the user moves the mouse. The row cursor is a value that represents which row in the table is the current row; use the Fetch statement to position the row cursor. See Dynamic Data Exchange (DDE).
295 User Guide
Client
Column
Comment
Compiler
Cosmetic Layer
DDE
MapBasic 10.5
Chapter F: MapBasic Glossary Terms Term Degrees Definition A unit of measure for map coordinate systems. Some paper maps depict coordinates in terms of degrees, minutes, seconds (for example, 42 degrees, 30 minutes); MapBasic statements, however, work in decimal degrees (for example, 42.5 degrees). See also: Latitude, Longitude. A column in a query table, produced by applying an expression to values already existing in the base table. See the Add Column statement. A condition where part of the user interface (a menu command, dialog box control, or toolbar button) is not available to the user. The disabled item is generally shown as grayed out to indicate that it is not available. See also: Enabled. Microsoft Windows-specific protocol that allows different applications to exchange instructions and data. Both applications must be DDE compliant for a successful exchange. Microsoft Windows files containing shared executable routines and other resources. DLLs are generally called from one program to handle a task which often returns a value back to the original program. The opposite of Disabled; a condition where a menu command, dialog box control, or toolbar button is available for use. A grouping of one or more variables, constant values, function calls, table references, and operators. The process of reading information from a file or writing information to a file. Note that the MapBasic language has one set of statements for performing file i/o, and another set of statements for performing table manipulation. In a dialog box, the active control (the control which the user is currently manipulating) is said to have the focus; pressing the Tab key moves the focus from one control to the next. Focus also refers to the active application that is running. Switching to a different application (for example, by pressing Alt-Tab on Windows) causes the other application to receive the focus. An area for file storage; also called a directory. A relational link between two mappable tables based on geographic criteria (for example, by determining which point objects from one table are inside of regions in the other table). A hardware/software system that receives satellite signals and uses the signals to determine the receivers location on the globe.
Derived Column
Disabled
Enabled
Expression
Focus
MapBasic 10.5
296
User Guide
Chapter F: MapBasic Glossary Terms Term Global Variable Definition A variable defined at the beginning of a program that can be used in any procedure or function. Created using the Global statement. A procedure in a program. When a specific event occurs (such as the user choosing a menu command), the handler performs whatever actions are needed to respond to the event. A base-16 number system, often used in computer programming. Each character in a hexadecimal number can be 0-9 or A-F. In MapBasic, you must begin each hexadecimal number with the &H prefix (for example, &H1A is a hexadecimal number that equals decimal 26). Technology that allows MapInfo Professional features, such as Map windows, to be integrated into other applications (such as Visual Basic programs). See Integrated Mapping. An IsoChrone is a polygon or set of points representing an area that can be traversed from a starting point in a given amount of time along a given road network. An IsoDistance is a polygon or set of points representing an area that can be traversed from a starting point travelling a given distance along a given road network. An Isogram is a map that displays a set of points that satisfy a distance or time condition. Isograms are either IsoChrones or IsoDistances. A word recognized as part of the programming language; for example, a statement or function name. In the MapBasic documentation, keywords appear in bold. A type of coordinate, measured in degrees, indicating north-south position relative to the Equator. Locations south of the Equator have negative latitude. A type of MapInfo table that is downloaded from a remote database. The data is taken from the remote database and transferred locally. The next time the table is linked back to the remote database, MapInfo Professional checks time stamps to see if there are any differences between the two tables. Where differences occur, the table is updated with the new information. A program that combines separate modules from a project file into a single MBX application file. An expression that defines a specific, explicit value. For example, 23.45 is a literal number, and Hello, World is a literal string. Also referred to as a hard-coded value.
297 User Guide
Handler
Hexadecimal
Integrated Mapping
IsoChrone
IsoDistance
Isogram
Keyword
Latitude
Linked Table
Linker
Literal Value
MapBasic 10.5
Chapter F: MapBasic Glossary Terms Term Local Variable Definition A variable that is defined and used within a specific function or procedure. Local variables take precedence over global variables of the same name. Created using the Dim statement. A type of coordinate, measured in degrees, indicating east-west position relative to the Prime Meridian. Locations west of the Prime Meridian have negative longitude. A control structure in a program that executes a group of statements repeatedly. Incorrect coding of a loop can create an infinite loop (a situation where the loop never ends). A window in the MapInfo Professional user interface. From MapInfo Professionals Options menu, choose Show MapBasic Window. You can type MapBasic statements into the MapBasic window, without compiling a program. A MapBasic executable file, which the user can run by choosing MapInfo Professionals Tools > Run MapBasic Program command. Any MapInfo Professional user can run an MBX file. To create an MBX file, you must use the MapBasic development environment. Information about a table (such as date of creation, copyright notice, etc.) stored in the .TAB file instead of being stored in rows and columns. See Working With Tables. Part of OLE Automation. Calling an applications methods is like calling a procedure that affects the application. See Integrated Mapping. A program file (.MB file) that is part of a project. A variable that can be accessed from any function or procedure in an MB program file, although it cannot be accessed from other MB program files in the same project. Created by placing a Dim statement outside of any function or procedure. A standard file format. Choosing MapInfo Professionals File > New command creates a native MapInfo table, but a table based on a spreadsheet or text file is not in MapInfos native file format. A graphical object is an entity that can appear in a Map or Layout window (for example, lines, points, circles, etc.). A MapBasic object variable is a variable that can contain a graphical object. The Object column name refers to the set of objects stored in a table. An OLE object is a Windows-specific entity (produced, for example, through drag and drop).
Longitude
Loop
MapBasic Window
MBX
Metadata
Native
Object
MapBasic 10.5
298
User Guide
Chapter F: MapBasic Glossary Terms Term Object Linking and Embedding (OLE) Definition Technology that allows objects created in one application to be used in another application. An object can be any information such as a map, chart, spreadsheet, sound effect, text, etc. Embedding is the process of inserting an object from a server into a container application. A special character or word that acts upon one or more constants, variables, or other values. For example, the minus operator () subtracts one number from another. Another word for argument. The line style set for an object. The style is comprised of width, pattern, and color. A circle divided into sectors representing values as percentages in comparison to one another. MapInfo Professional can display pie charts in the Graph window or in thematic maps. An operating environment for computer software (for example, Windows, Linux). A group of statements enclosed within a SubEnd Sub construction. Sometimes referred to as a routine or a subroutine. A standard dialog box that displays a horizontal bar, showing the percent complete. A project is a collection of modules. A project file (.MBP file) is a text file that defines the list of modules. Compiling all modules in the project and then linking the project produces an application (MBX) file.
Operator
Pie Chart
Platform
Property, OLE Property Part of OLE Automation. A property is a named attribute of an OLE object. To determine the objects status, read the property. If a property is not read-only, you can change the objects status by assigning a new value to the property. See Integrated Mapping. Raster Raster Underlay Table A graphic image format that consists of rows of tiny dots (pixels). A table that consists of a raster image. This table does not contain rows or columns; therefore, some MapBasic statements that act on tables cannot be used with raster underlay tables. An entry in a table or database. Each record appears as one row in a Browser window.
Record
MapBasic 10.5
299
User Guide
Chapter F: MapBasic Glossary Terms Term Recursion Definition A condition where a function or procedure calls itself. While recursion may be desirable in some instances, programmers should be aware that recursion may occur unintentionally, especially with special event handlers such as SelChangedHandler. Data stored in a remote database, such as an Oracle or SYBASE server. A group of statements that performs a specific task; for example, you can use the OnError statement to designate a group of statements that will act as the error-handling routine. Another word for record. The time at which a program is executing. A runtime error is an error that occurs when an application (MBX file) is running. A special version of MapInfo Professional that contains all of the geographic and database capabilities of a full version but does not include the specific menu and toolbar options in a standard package. Used to create customized versions of MapInfo Professional. Refers to whether a variable can be accessed from anywhere within a program (global variables) or only from within a specific function or procedure (local variables). If a procedure has a local variable with the same name as a global variable, the local variable takes precedence; any references to the variable name within the procedure will use the local variable. A type of table that groups other tables together, making it easier to open and map several tables at one time. See Working With Tables. An application that performs operations for or sends data to another application (the client). Often referred to in database connections or DDE connections. A menu that appears if the user clicks the right mouse button. The uncompiled text of a program. In MapBasic, the .MB file. Standard menu commands and standard toolbar buttons appear as part of the default MapInfo Professional user interface (for example, File > New is a standard menu command). Standard dialog boxes are dialog boxes that have a predefined set of controls (for example, the Note statement produces a standard dialog box with one static text control and an OK button). If a MapBasic program creates its own user interface element (dialog box, toolbar button, etc.) that element is referred to as a custom dialog box, a custom button, etc.
300 User Guide
Remote Data
Routine
Runtime
Scope of Variables
Seamless Tables
Server
MapBasic 10.5
Chapter F: MapBasic Glossary Terms Term Statement Definition An instruction in a MapBasic program. In a compiled MapBasic program, a statement can be split across two or more lines. The bar along the bottom of the MapInfo Professional program window which displays help messages, the name of the editable layer, etc. A help message that appears on the status bar when the user highlights a menu command or places the mouse cursor over a toolbar button. A group of statements; in MapBasic syntax, subroutines are known as procedures or sub procedures. A set of buttons. The user can dock a toolbar by dragging it to the top edge of the MapInfo Professional work area. The MapBasic documentation often refers to Toolbars as ButtonPads because ButtonPad is the MapBasic-language keyword that you use to modify toolbars. A brief description of a toolbar button; appears next to the mouse cursor when the user holds the mouse cursor over a button. A fill pattern, such as a striped or cross-hatch pattern, that is not completely opaque, allowing the user to see whatever is behind the filled area. A small area of memory allocated to store a value.
Status Bar
Subroutine
Toolbar
ToolTip
Transparent Fill
Variable
MapBasic 10.5
301
User Guide
Index
(minus) 277 date subtraction 55 subtraction 54 = (equal sign) 56 > (greater than) 56 >= (greater than or equal) 56 \ (backslash) integer division 54, 277 ^ (caret) 54 exponentiation 277 (apostrophe) 43
Symbols
& (ampersand) finding an intersection 129 hexadecimal numbers 51 shortcut keys in dialog boxes 102 shortcut keys in menus 90 string concatenation 55, 277 * (asterisk) fixed-length strings 45 multiplication 54, 277 + (plus) 277 addition 54 date addition 55 string concatenation 55 , (comma) character thousand separator 51 . (period) character decimal separator 51 .Net Programmability building and copying the assembly file 251 calling a method by alias 252 creating a class in 250 declaring and calling a method from MapBasic 251 exception handling 258 getting started in 249 introduction 249 passing arguments to .Net 253 passing custom variable types to .Net 254 performance notes 254 restrictions of passing structures to .Net 257 terminology 249 / (forward slash) date string format 52 division 54, 277 < (less than) 56 < > (not equal) 56 <= (less than or equal) 56
MapBasic 10.5 302
A
Accelerator keys in dialog boxes 102 in integrated mapping 214 in menus 90 Accessing remote databases 147 Add Column statement 186 Add Map Layer statement 105 Adding columns to a table 131 Adding nodes to an object 170 Addresses, finding 129 Advise loops MapInfo as DDE server 200 Aggregate functions 294 See MapBasic Reference Guide Alias 294 column references 126 variables 126 Alias, calling a method by 252 Alter Button statement 111 Alter ButtonPad statement 111, 194 Alter Control statement 101 Alter Menu Bar statement 85 Alter Menu Item statement 86 Alter Menu statement 84 Alter Object statement 170, 174 Alter Table statement 131 And operator 57 Animation layers 105 Any( ) operator 185 Area units 181 Area( ) function 184 Area( ) function 163
User Guide
Arguments passing by reference 65 passing by value 66 passing to .Net 253 Arithmetic operators 54 Array variables declaring 46 resizing 46 Ask( ) function 93 Assembly File, building and copying 251 Assigning values to variables 44 auto_lib.mb (sample program) 120 AutoLabel statement 170 Automation 294 object model 223
B
Bar charts in graph windows 107 in thematic maps 105 Beeping because window is full 30 Between operator 56 BIL (SPOT image) files 140 Binary file i/o 154, 157 Bitmap image files 140 Branching 61 Breakpoints (debugging) 77 Browser windows 107 Brush styles 163 BrushPicker controls 98 Buffers, creating 172, 272 Button controls (in dialog boxes) 99 ButtonPads adding new buttons 113 creating new pads 112 custom Windows icons 194 defined 295 docking 118 help messages for buttons 117 ICONDEMO.MBX 115 PushButtons 110 ToggleButtons 111 ToolButtons 111 By-reference parameters 65 By-value parameters 66
C
C language sample programs 247 Callbacks 214 Calling a Method from MapBasic 251 Calling external routines 36, 189 Calling procedures 64
MapBasic 10.5 303
CancelButton controls 99 Case sensitivity 43 Character sets 157 Checkable menu items 86 CheckBox controls 99 Circles See Objects 13 Class creating in .Net 250 Class name MapInfo.Application 206 MapInfo.Runtime 206 Clicking and dragging 113 Client/server database access 147 DDE protocol 195 Close Window statement 104, 201 Color values RGB( ) function 167 selecting objects by color 167 Columns alias expressions 126 Obj (object) column 128, 160 RowID column 128 syntax for reading 126 Command line arguments 32, 239 CommandInfo( ) function ButtonPads 111 DDE 200 detecting double-click in list 100 detecting if user clicked OK in dialog box 95 determining Find results 129 ID of selected menu item 89 Comments 43 Commit statement 108, 130 Commit Table statement 105 Comparison operators 56 Compiler 295 Compiler directives 72 Compiling a program from the command line 32 in the active window 21, 30 without opening the file 38 Concatenating strings & operator 277 + operator 277 Confirmation prompt 93 Connecting to a remote database 147 Connection handle 147 Connection number 147 Constants date 52 defined 49 logical 52
User Guide
numeric 51 string 51 Contains operator 58, 183 Continue statement 76 Continuous Thematic Shading support 105 Control panels, effect on date formatting 53 Controls EditText 97 GroupBox 97 StaticText 97 Controls in dialog boxes 96 Conventions 17 Coordinate systems earth coordinates 180 Layout coordinates 136, 180 non-earth coordinates 180 Copying programs from Help 24 Cosmetic layer defined 295 deleting objects from 135 selecting objects from 135 Create ButtonPad statement 111, 113, 194 Create Frame statement 108, 169 Create Index statement 130 Create Map statement 130, 161 Create Menu Bar statement 88 Create Menu statement 85 Create Text statement 108, 164 CreateCircle( ) function 170 Creating a class in .Net 250 Creating map objects 169 Crystal Report writer 124 CurDate( ) function 55 CurDate( ) function 51 Cursor (drawing-tool icon) 118 Cursor (position in table) 125 Custom Variable Types, passing to .Net 254
D
Data structures 47 Database live access 150 Date constants 52 Date operators 55 DBF (dBASE) files 124 DDE acting as client 196, 200 acting as server 200 Debugging a program 76 Decimal separators in numeric constants 51 Decision-making Do Case statement 60
MapBasic 10.5 304
IfThen statement 59 Declare Function statement 71, 188 Declare Sub statement 64, 188 Declaring a Method from MapBasic 251 Define statement 72 Degrees 296 Degrees to DMS 270 Deleting columns from a table 131 files 155 indexes 132 menu items 84, 91 menus 87, 91 part of an object 175 Delphi sample programs 247 Dialog boxes, custom control types 96 disabled controls 101 examples 95 lists based on arrays 101 lists based on strings 101 modal vs. modeless 102 positions of controls 95 reacting to users actions 100 reading final values 100 setting initial values 99 shortcut keys 102 sizes of controls 95 terminating 103 Dialog boxes, standard asking OK/Cancel question 93 hiding progress bars 121 opening a file 93 percent complete 94 saving a file 94 simple message 93 Dim statement 44 Directory names 155 Disabled, defined 296 Distance units 181 DLLs declaring 188 defined 188 Kernel library 191 passing parameters 189 search path 188 storing ButtonPad icons 194 string parameters 190 User library 189 DMS to Degrees 270 Do Case statement 60 DoLoop statement 62 Dockable ButtonPads 118
User Guide
E
Edit menu 38 Editing target 175 EditText controls 97 Embedding 205 Enabled 296 End Program statement 63 EndHandler procedure 68 EOF( ) function (end of file) 156 EOT( ) function (end of table) 125 Erasing a file 155 Erasing part of an object 175 Err( ) function 78 Error$( ) function 78 Errors compile-time 31 run-time 76, 130 trapping 78 ERRORS.DOC 212 Events, handling defined 67 selection changed 116 special procedures 68 user-interface events 81 Excel files 124 Execution speed, improving handler procedures 70 table manipulation 150 user interface 120 External references routines in other modules 36 Windows DLLs 188
F
Fetch statement 125, 174 File extensions 15 File input/output binary file i/o 157 character sets 157 copying a file 155 defined 154 deleting a file 155 random file i/o 156 renaming a file 155 sequential file i/o 155 File menu 37 FileExists( ) function 155 FileOpenDlg( ) function 93 Files, external
MapBasic 10.5 305
BIL (SPOT image) 140 DBF (dBASE) 124 GIF 140 JPG 140 PCX 140 Targa 140 TIFF 140 WKS (Lotus) 124 XLS (Excel) 124 FileSaveAsDlg( ) function 94 Fill styles (Brush) 163 Find and replace in MapBasic editor 38 sample program 273 Finding a street address 129 Fixed-length string variables 46 Focus defined 296 within a dialog box 101 Font styles 163164 FontPicker controls 98 ForNext statement 61 ForegroundTaskSwitchHandler procedure 68 Foreign character sets 157 Format$( ) function 107 FoxBase files 124 Frame objects 169 FrontWindow( ) function 104 FunctionEnd Function statement 71 Functions Area( ) 163 CreateCircle( ) 170 CurDate( ) 51 EOF( ) 156 EOT( ) 125 Err( ) 78 Error$( ) 78 FileExists( ) 155 FileOpenDlg( ) 93 FileSaveAsDlg( ) 94 Format$( ) 107 FrontWindow( ) 104 GetMetaData$( ) 143 GetSeamlessSheet( ) 146 IntersectNodes( ) 176 LabelFindByID( ) 177 LabelFindFirst( ) 177 LabelFindNext( ) 177 LabelInfo( ) 177 MakePen( ) 167 NumberToDate( ) 52 ObjectGeography( ) 162 ObjectInfo( ) 162, 167
User Guide
ObjectLen( ) 163, 184 Perimeter( ) 163 ReadControlsValue( ) 100 ReadControlValue( ) 102 RemoteQueryHandler( ) 199 RTrim$( ) 57 scope 71 SearchInfo( ) 116 SelectionInfo( ) 133 StyleAttr( ) 164, 167 TableInfo( ) 128, 146, 161 TempFileName$( ) 155 TriggerControl( ) 100 UBound( ) 46 user-defined 71 WindowID( ) 104 WindowInfo( ) 104, 136
I
Icons for ButtonPads 113, 193 Identifiers, defining 72 IfThen statement 59 Images (raster) 140 Include statement 72 Indexes, creating 130, 132 Infinite loops, preventing 70 Info window customizing 109 making read-only 109 Input # statement 156 Input/output, See File input/output Insert statement 108, 130, 171 Inserting columns into a table 131 nodes in an object 170 rows into a table 130 Installation instructions 15 Integer division 277 Integer math 54 Integrated Mapping defined 297 error trapping 212 introduction 203 MFC 240 object model 223 online Help 219 printing 212 reparenting document windows 207 reparenting legend windows 208 resizing windows 209 sample programs 205, 247 starting MapInfo 206 stopping MapInfo 213 system requirements 204 toolbar buttons 210 using callbacks 214 International character sets 157 Intersection area where objects overlap 172 Intersects operator 58 of two streets 129 points where lines intersect 176 IntersectNodes( ) function 176 Intersects operator 58, 183 Introduction to MapBasic 20
G
Geocoding automatically 129 interactively 129 MapMarker 129 Geographic objects, See Objects Geographic operators 58, 182 Get statement (file i/o) 157 GetMetaData$( ) function 143 GetSeamlessSheet( ) function 146 GIF files 140 Global Assembly Cache (GAC), loading 259 Global variables 48 GoTo statement 61 GPS 296 GPS applications 105 Graduated symbol maps 105 Graph windows 107 Graticules (grids) 270 Grid Thematic support 105 GroupBox controls 97
H
Halting a program 63 Header files 15 Height of text 164 Help files creating 201 using 24 Help menu 40 Help messages for buttons 117 Hexadecimal numbers 297 &H syntax 51 Hot keys
MapBasic 10.5 306
User Guide
J
Joining tables 185 JPG files 140
M
Main procedure 64 MakePen( ) function 167 Map Catalog 283 Map objects, See Objects Map projections 105 Map windows 104 labeling 176 See Layers MapBasic Window 44 MapInfo documentation set 16 MapInfo menus file 91 MapInfo Professional technical support 18 MapInfo Runtime launching through OLE 206 MapInfo-L archive 19 MAPINFOW.MNU file 91 MapMarker product 129 MBX file defined 298 Memory limitations 30 Menus, customizing adding menu items 84 altering a menu item 86 altering the menu bar 87 creating new menus 85 MAPINFOW.MNU file 91 removing menu items 84 shortcut keys 90 Merging objects 172 message URL http //www.pbinsight.com 15 Message window 108 Metadata 142 Methods Application object 226 calling by alias 252 declaring and calling from MapBasic 251 defined 298 MBApplication object 232 MIMapGen object 235 Metric units 180 MFC getting started 240 sample programs 247 Microsoft Excel DDE conversations 196 worksheet files 124
307 User Guide
K
Kernel (Windows DLL) 191 Keyboard shortcuts 28 Kill statement 155 Kilometers 180
L
LabelFindByID( ) function 177 LabelFindFirst( ) function 177 LabelFindNext( ) function 177 Labelinfo( ) function 177 Labels converting to text 178 in programs 61 on maps 170, 176 Latitude 297 Layers adding/removing layers 105 Cosmetic layer 135 thematic layers 105 Layout windows object coordinates 180 opening 108 treating as tables 135 Legend windows, managing 271 Length of an object 184 Like operator 55 Line Input # statement 156 Line numbers in a program 39 Line objects, See Objects Line styles (Pen) 163 Linked tables 149 defined 297 Linker 297 Linking a project after selecting a current project 35 from the command line 32 without opening the file 38 ListBox controls 98, 101 Literal value 297 Live remote database access 150 Local variables 44 Logical operators 57 Longitude 298 Looping DoLoop statement 62 ForNext statement 61
MapBasic 10.5
Mod (integer math) 54 Mod operator 277 Modal dialog boxes 102 Module 298 Modules calling functions/procedures from other 36 declaring variables that cannot be shared with other 37 sharing variables with other 36 Mouse events choosing a menu item 83 clicking and dragging 113 double-clicking on a list 100 Mouse shortcuts 29 Moving an object 174 MultiListBox controls 98, 101 Multi-user editing 136
N
Nodes adding 170, 176, 273 determining coordinates 176 maximum number of 170 NoSelect keyword 70 Not operator 57 Note statement 93 Number of nodes per object 170 objects per row 162 open windows 104 polygons per region 162 sections per polyline 162 selected rows 133 NumberToDate( ) function 52 Numeric constants 51 Numeric operators 54
O
Object Model 223 Object variables 160 ObjectGeography( ) function 162 ObjectInfo( ) function 162, 167 ObjectLen( ) function 163, 184 Objects, creating based on existing objects 172 buffers 172 creation functions 170 creation statements 169 storing in a table 171 Objects, deleting 161 Objects, modifying adding nodes 170, 176
MapBasic 10.5 308
combining 172 erasing part of an object 175 position 174 storing in a table 171 style 174 type of object 175 Objects, querying coordinates 162 styles 163 types 162 ODBC connectivity, data types supported 281 OKButton controls 99 OLE Automation 223 defined 294 OLE Embedding 205 OnError statement 78 On-Line Help creating 201 using 24 Open File statement 154 Open Window statement 103, 201 Opening a table 123 Opening multiple files 36 Operators comparison 56 date 55 defined 50 geographic 58, 182 logical 57 numeric 54 precedence 58 string 55 Optimizing performance handler procedures 70 table manipulation 150 user interface 120 Or operator 57 Order of evaluation 58
P
Pack Table statement 128 Page layouts 108 Paper units 181 Parameters passing by reference 65 passing by value 66 Passing Structures custom variable types to .Net 254 Passing Structures to .Net, restrictions 257 Pattern matching 55 PCX files 140 Pen styles 163
User Guide
PenPicker controls 98 Percent-complete dialog box 94 Performance tips handler procedures 70 table manipulation 150 user interface 120 Perimeter( ) function 163 Pie charts in graph windows 107 in thematic maps 105 Point objects, See Objects Point styles (Symbol) 163 Points of intersection 176 Points, storing in a remote database 149 Polygon overlay 186 Polyline objects, See Objects PopupMenu controls 98, 101 PowerBuilder, sample programs 247 Precedence of operators 58, 279 Print # statement 156 Print statement 108 Procedures calling 64 defined 64 Main 64 passing parameters 65 recursion 66 that handle events 67 Product training 25 Program organization 73 Progress bar defined 299 hiding 121 ProgressBar statement 94 Project files benefits of 33 creating 34 defined 33 examples 34 linking 35 Project menu 39 Projections, changing 105 Properties Application object 225 defined 299 MBApplication object 231 MBApplications collection 231 MBGlobal object 233 MBGlobals collection 232 MIMapGen object 234 Proportional data aggregation 186 PushButtons 110 Put statement (file i/o) 157
MapBasic 10.5 309
Q
QueryN tables closing 133 opening 133 Quick Start dialog box 119
R
RadioGroup controls 98 Random file i/o 154, 156 Raster underlay table 299 Raster underlay tables 140 ReadControlValue( ) function 100, 102 Reading another applications variables 199 Realtime applications 105 Records, See Rows Recursion 66 defined 300 ReDim statement 46 Redistricting windows 108 Region objects, See Objects Relational joins 161, 185 Remarks 43 Remote data, defined 300 Remote database access 147 Remote database live access 150 RemoteMsgHandler procedure, DDE 200 RemoteQueryHandler( ) function 199 Remove Map Layer statement 105 Rename File statement 155 Report writer 124 Responding to events, See Events, handling Resume statement 78 Retry/Cancel dialog box 136 RGB color values 167 Right-click menus destroying 89 modifying 88 RollBack statement 130 Rotating a graphical object 272 Row cursor, positioning 125 RowID 128 Rows in a table displaying in Info window 109 inserting new rows 130 row numbers (RowID) 128 setting the current row 125 sorting 130 updating existing rows 130 RTrim$( ) function 57 Run Application statement 119 Run Menu Command statement 90, 108 Running a program
User Guide
from MapInfo 21, 31 from the development environment 40 from the startup workspace 119 Run-time errors 76 Runtime executable launching through OLE 206
S
Sample programs, integrated mapping 247 Save File statement 155 Scope of functions 71 Scope of variables 49 Scroll bars, showing or hiding 105 Seagate Crystal Report writer 124 Seamless tables 145 Search and replace in MapBasic editor 38 sample program 273 Search menu 38 Search path for DLLs 188 SearchInfo( ) function 116 SelChangedHandler procedure 68, 116 Select Case (Do Case) 60 Select statement 161162, 169, 182184 Selection changing 134 clicking on an object 115 querying 135 SelectionInfo( ) function 133 Sequential file i/o 154155 Set CoordSys statement 136, 180 Set Event Processing statement 106 Set File Timeout statement 138 Set Format statement 52 Set Map statement 105106, 170 Set Redistricter statement 108 Set Shade statement 105 Set Table statement 146 Set Target statement 175 Set Window statement 104, 201 Shade statement 105 Sharing conflicts 136 Shortcut keys in dialog boxes 102 in menus 90 Shortcut menus destroying 89 modifying 88 Simulating a menu selection 90 Size limitations 30 Size of text 164 Snap to Node 214
MapBasic 10.5 310
Sorting rows in a table 130 Source code 300 Speed, improving handler procedures 70 table manipulation 150 user interface 120 SPOT image files 140 Spreadsheet files, opening 124 SQL Select queries 130 Startup workspace 119 Statement handle 147 Statement number 147 Statements 301 Add Column 186 Add Map Layer 105 Alter Button 111 Alter ButtonPad 111, 194 Alter Control 101 Alter Menu Bar 85 Alter Menu Item 86 Alter Object 170, 174 Alter Table 131 AutoLabel 170 Close Window 104, 201 Commit 108, 130 Continue 76 Create ButtonPad 111, 113, 194 Create Frame 108, 169 Create Index 130 Create Map 130, 161 Create Menu 85 Create Menu Bar 88 Create Text 108, 164 Declare Function 71, 188 Declare Sub 64, 188 Define 72 Dim 44 Do Case 60 DoLoop 62 Drop Map 161 End Program 63 Fetch 125, 174 ForNext 61 FunctionEnd Function 71 GoTo 61 IfThen 59 Include 72 Input # 156 Insert 108, 130, 171 Kill 155 Line Input # 156 Note 93 OnError 78
User Guide
Open File 154 Open Window 103, 201 Pack Table 128 Print 108 Print # 156 ProgressBar 94 ReDim 46 Remove Map Layer 105 Rename File 155 RollBack 130 Run Application 119 Run Menu Command 90, 108 Save File 155 Select 161162, 169, 182, 184 Set CoordSys 136, 180 Set Event Processing 106 Set File Timeout 138 Set Format 52 Set Map 105106, 170 Set Redistricter 108 Set Shade 105 Set Table 146 Set Target 175 Set Window 104, 201 Shade 105 Stop 76 TypeEnd Type 47 Update 130, 170, 174 WhileWend 63 Write # 156 StaticText controls 97 Status bar help messages 117 in Integrated Mapping 215 Stop statement 76 Stopping a program 63 Storing points on an RDBMS table 283 Storing points on remote databases 149 Street addresses, finding 129 String concatenation & operator 277 + operator 277 String constants 51 String operators 55 String variables, fixed- vs. variable-length 46 StringCompare( ) function 57 Structures 47 StyleAttr( ) function 167 StyleAttr( ) function 164, 167 Styles (Pen, Brush, Symbol, Font) 163 Styles, comparing 164 Sub procedures, See Procedures Subselects 184 Subtotals, calculating 130
MapBasic 10.5 311
T
TableInfo( ) function 161 TableInfo( ) function 128, 146, 161 Tables adding dynamic columns 131 adding permanent columns 131 adding temporary columns 131 based on spreadsheets and database files 124 closing QueryN tables 133 column expressions 126 component files 140 Cosmetic 135 creating 130 joining 185 layout 135 making mappable 130 metadata 142 number of open tables 132 Obj (object) column 128, 160 opening 123 raster image tables 140 reading values 125 row numbers 128 Selection 133 structure, modifying 131 structure, querying 132 writing values 130 Targa files 140 Target objects 175 Technical Support services 1819 technical support obtaining 18 offerings 18 TempFileName$( ) function 155 Text editors 32 Text height 164 Text objects 163, 174 See Objects Text styles (Font) 163 Thematic maps 105 Thousand separators, in numeric constants 51 TIFF files 140 ToggleButtons defined 111 Toolbars, See ButtonPads ToolButtons defined 111 ToolHandler procedure 68, 112
User Guide
ToolTips 117 Totals, calculating 130 Transparent fill 301 Trapping run-time errors 78 TriggerControl( ) function 100 Type conversion 54 TypeEnd Type statement 47 Typographical conventions 17
U
UBound( ) function 46 Ungeocoding 161 Units of measure area units 181 distance units 181 paper units 181 Update statement 130, 170171, 174 Updating remote databases 149 User (Windows DLL) 189 User interface ButtonPads 110 dialog boxes, custom 95 dialog boxes, standard 93 menus 83 overview 81 windows 103 User-defined functions 71 User-defined types 47
WinChangedHandler procedure 68 WinClosedHandler procedure 68 Window identifiers 104 Window menu 40 WindowID( ) function 104 WindowInfo( ) function 104, 136 Windows, customizing Browser 107 Graph 107 Info window 109 Layout 108 Map 104 Message 108 Redistricter 108 size and position 104 WinFocusChangedHandler procedure 68 Within operator 58, 183 WKS files, opening 124 Workspaces startup 119 using as sample programs 24 Write # statement 156
X
XLS files, opening 124
V
Variable-length string variables 46 Variables declarations 44 defined 44 global 48 list of data types 45 object variables 160 reading another applications globals 199 restrictions on names 45 scope 49 style variables 166 Vertices, See Nodes Visual Basic sample programs 205, 247 Visual C++ getting started 240 sample programs 247
W
Warm links 200 WhileWend statement 63 Wildcards (string comparison) 55 WIN.INI file, querying settings 191
MapBasic 10.5 312 User Guide