Using AutoCAD's file selection dialog from .NET

 

Today I started putting together some code showing how to link an Excel sheet to an AutoCAD table (watch this space - there should be something posted later this week). As I was working through it I decided enough was enough, and rather than - yet again - using the command-line to get the name of the file, I'd use the opportunity to demonstrate how to make use of AutoCAD's standard file selection dialog in your applications.

At which point I decided to cut the original post short, as I didn't want this useful (but quite short) topic to get swamped by the broader one.

Here's the C# code that asks the user to select an Excel spreadsheet:

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.Windows;

 

namespace OpenFiles

{

  public class Commands

  {

    [CommandMethod("SS")]

    static public void SelectSpreadsheet()

    {

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Database db = doc.Database;

      Editor ed = doc.Editor;

 

      OpenFileDialog ofd =

        new OpenFileDialog(

          "Select Excel spreadsheet to link",

          null,

          "xls; xlsx",

          "ExcelFileToLink",

          OpenFileDialog.OpenFileDialogFlags.DoNotTransferRemoteFiles

        );

 

      System.Windows.Forms.DialogResult dr =

        ofd.ShowDialog();

 

      if (dr != System.Windows.Forms.DialogResult.OK)

        return;

 

      ed.WriteMessage(

        "/nFile selected was /"{0}/".",

        ofd.Filename

      );

    }

  }

}

A few notes on the arguments to the OpenFileDialog constructor:

  1. The first string is the one shown in the title bar (see below)
  2. You can pass in a default filename in the second argument, but in our case it isn't appropriate
  3. You can provide multiple file extensions upon which to filter in the third argument, separated by semi-colons
  4. The fourth argument is an internal identifier used to store data about the dialog, such as size, position and last navigated path (this data will be picked up automatically the next time the identifier is used)
  5. The fifth argument is for flags: we're choosing not to copy remote files locally if selected via a URL, in this case

If we were opting to allow multiple file selection (passing AllowMultiple as an additional flag to the fifth argument), then we would access the files returned using ofd.GetFileNames() to access an array of strings.

Here's the dialog we see when we run the SS command:

Open_file_dialog

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值