コード例 #1
0
        public string BrowseDestination(Window owner, string destination, string extension)
        {
            using (var dialog = new FileSaveDialog())
            {
                GetFilePathInfo(destination, out var folderPath, out var fileName, out var fileExtension);

                dialog.SetClientGuid(new Guid("486640B6-B311-4EFD-A15F-616F51FAAF5B"));
                dialog.SetDefaultFolder(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
                dialog.SetTitle("Destination file of the image to be created");
                dialog.SetOkButtonLabel("Select");
                dialog.SetCancelButtonLabel("Cancel");
                dialog.SetFileNameLabel("Destination file :");
                dialog.SetDefaultExtension(extension.Substring(1));
                dialog.SetFileTypes($"Image files (*{extension})|*{extension}|All files (*.*)|*.*");
                dialog.SetFileTypeIndex(fileExtension == null || fileExtension.Equals(extension, StringComparison.OrdinalIgnoreCase) ? 1 : 2);
                dialog.DontAddToRecent = true;

                if (fileName != null)
                {
                    dialog.SetFileName(fileName);
                }

                if (PathHelper.DirectoryExists(folderPath))
                {
                    dialog.SetFolder(folderPath);
                }

                return(dialog.ShowDialog(owner) == true?dialog.GetResult() : null);
            }
        }
コード例 #2
0
        public void DownloadFile(byte[] fileBytes)
        {
            Invoke((Action)(() => { FileSaveDialog.ShowDialog(); }));
            var myStream = FileSaveDialog.OpenFile();

            myStream.Write(fileBytes, 0, fileBytes.Length);
            myStream.Close();
        }
コード例 #3
0
        public void showSaveFileDialog(string filterString, SendResult <string> resultCallback)
        {
            FileSaveDialog dlg = new FileSaveDialog(wildcard: filterString);

            dlg.showModal((mResult, mFiles) =>
            {
                saveResults(mResult, mFiles, resultCallback, dlg);
            });
        }
コード例 #4
0
        public static string GetFileName()
        {
            FileSaveDialog fsd = new FileSaveDialog("Text Files (*.txt)|*.txt");

            fsd.Title = "Database File";
            fsd.Show();
            ModelPath mp       = fsd.GetSelectedModelPath();
            string    filename = ModelPathUtils.ConvertModelPathToUserVisiblePath(mp);

            return(filename);
        }
コード例 #5
0
        private void exportToJson()
        {
            FileSaveDialog saveDialog = new FileSaveDialog(controller.MainWindow);

            saveDialog.showModal((result, path) =>
            {
                if (result == NativeDialogResult.OK)
                {
                    controller.saveModelJSON(path);
                }
            });
        }
コード例 #6
0
        /// <summary>Executes a SaveAs operation.</summary>
        /// <remarks>After saving, the timing mode is set to the timing mode of the subtitle format using when saving.</remarks>
        /// <returns>Whether the file was saved.</returns>
        public bool SaveAs()
        {
            FileSaveDialog dialog     = Base.Dialogs.Get(typeof(FileSaveDialog)) as FileSaveDialog;
            FileProperties properties = ShowSaveAsDialog(dialog);

            if (properties != null)
            {
                Save(properties);
                return(true);
            }

            return(false);
        }
コード例 #7
0
        /// <summary>
        /// This will show the save file dialog and will return the newly chosen file.
        /// </summary>
        /// <param name="parent">The parent window.</param>
        /// <returns>The current file or null if the user canceled the dialog.</returns>
        public void saveFileAs(FileChosen fileChosenCb)
        {
            FileSaveDialog save = new FileSaveDialog(ParentWindow, "", DefaultDirectory, "", Filter);

            save.showModal((result, file) =>
            {
                if (result == NativeDialogResult.OK && !String.IsNullOrEmpty(file))
                {
                    currentFile = file;
                    fileChosenCb(currentFile);
                }
            });
        }
コード例 #8
0
        private void FileDialogButton_Click(object sender, EventArgs e)
        {
            FileSaveDialog.ShowDialog();

            var path = FileSaveDialog.FileName;

            if (string.IsNullOrWhiteSpace(path))
            {
                return;
            }

            FileNameTextBox.Text = path.Trim();
            SetFileTypeBasedOnExtension(path);
        }
コード例 #9
0
ファイル: MaxExport.cs プロジェクト: AnomalousMedical/Medical
        void saveAllVisible_MouseButtonClick(Widget source, EventArgs e)
        {
            FileSaveDialog saveDialog = new FileSaveDialog(MainWindow.Instance, "Dump Positions to 3ds Max", Environment.CurrentDirectory, "AnomalousMedicalSimObjects.ms", "MaxScript (*.ms)|*.ms");

            saveDialog.showModal((result, path) =>
            {
                if (result == NativeDialogResult.OK)
                {
                    using (MaxWriter maxWriter = new MaxWriter(path))
                    {
                        maxWriter.write(AnatomyManager.AnatomyList.Where(a => a.CurrentAlpha > 0.0f).Select(a => new MaxWriterInfo(a.Owner)));
                    }
                }
            });
        }
コード例 #10
0
ファイル: MaxExport.cs プロジェクト: AnomalousMedical/Medical
        void saveAll_MouseButtonClick(Widget source, EventArgs e)
        {
            FileSaveDialog saveDialog = new FileSaveDialog(MainWindow.Instance, "Dump Positions to 3ds Max", Environment.CurrentDirectory, "AnomalousMedicalSimObjects.ms", "MaxScript (*.ms)|*.ms");

            saveDialog.showModal((result, path) =>
            {
                if (result == NativeDialogResult.OK)
                {
                    using (MaxWriter maxWriter = new MaxWriter(path))
                    {
                        maxWriter.write(medicalController.SimObjects.Select(so => new MaxWriterInfo(so)));
                    }
                }
            });
        }
コード例 #11
0
        public override void clicked(TaskPositioner taskPositioner)
        {
            FileSaveDialog saveDialog = new FileSaveDialog(MainWindow.Instance, "Save Microcode Cache", Environment.CurrentDirectory, Root.getSingleton().getRenderSystem().Name + ".mcc", "Microcode Cache (*.mcc)|*.mcc");

            saveDialog.showModal((result, path) =>
            {
                if (result == NativeDialogResult.OK)
                {
                    using (Stream stream = File.Open(path, FileMode.Create, FileAccess.Write))
                    {
                        GpuProgramManager.Instance.saveMicrocodeCache(stream);
                    }
                }
                fireItemClosed();
            });
        }
コード例 #12
0
        public void Save()
        {
            OnDisable();
            Filter[] filters   = new ShellFileDialogs.Filter[] { new ShellFileDialogs.Filter("JSON", "json"), new ShellFileDialogs.Filter("All files", "*") };
            string   selection = FileSaveDialog.ShowDialog(System.IntPtr.Zero, "Save VMC protocol dump", initialDirectory: Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), defaultFileName: "packets.json", filters: filters, selectedFilterZeroBasedIndex: 0);

            if (selection == null || selection == "")
            {
                OnEnable();
                return;
            }
            string json = JsonConvert.SerializeObject(messages, Formatting.Indented);

            File.WriteAllText(selection, json);
            OnEnable();
        }
コード例 #13
0
 void save_MouseButtonClick(Widget source, EventArgs e)
 {
     if (recordingSequence != null)
     {
         FileSaveDialog saveDialog = new FileSaveDialog(MainWindow.Instance, message: "Save Recorded Sequence", wildcard: "Movement Sequence (*.seq)|*.seq");
         saveDialog.showModal((result, path) =>
         {
             if (result == NativeDialogResult.OK)
             {
                 using (Stream stream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None))
                 {
                     SharedXmlSaver.Save(recordingSequence, stream);
                 }
             }
         });
     }
 }
コード例 #14
0
ファイル: MaxExport.cs プロジェクト: AnomalousMedical/Medical
        private void finishTransformedSave(Dictionary <String, MaxWriterInfo> transforms)
        {
            FileSaveDialog saveDialog = new FileSaveDialog(MainWindow.Instance, "Dump Positions to 3ds Max", Environment.CurrentDirectory, "AnomalousMedicalSimObjects.ms", "MaxScript (*.ms)|*.ms");

            saveDialog.showModal((result, path) =>
            {
                if (result == NativeDialogResult.OK)
                {
                    using (MaxWriter maxWriter = new MaxWriter(path))
                    {
                        maxWriter.write(from so in medicalController.SimObjects
                                        where transforms.ContainsKey(so.Name)
                                        select transformWriter(new MaxWriterInfo(so), transforms));
                    }
                }
            });
        }
コード例 #15
0
 private void ExportToFileButton_Click(object sender, EventArgs e)
 {
     FileSaveDialog.InitialDirectory = Directory.GetCurrentDirectory();
     if (FileSaveDialog.ShowDialog() == DialogResult.OK)
     {
         try
         {
             JsonFileSerializer.SerializeSnapshotsToJson(ImportedDatabase, FileSaveDialog.OpenFile());
         }
         catch (Exception Ex)
         {
             if (Ex is JsonSerializationException || Ex is JsonReaderException)
             {
                 GUIHelper.ThrowWarning("File error", "Serialization failed.");
             }
         }
     }
 }
コード例 #16
0
        /// <summary>Displays a SaveAs dialog and gets the chosen options as <cref="FileProperties" />.</summary>
        /// <param name="dialog">The dialog to display.</param>
        /// <returns>The chosen file properties, or null in case SaveAs was canceled.</returns>
        private FileProperties ShowSaveAsDialog(FileSaveDialog dialog)
        {
            dialog.Show();
            bool toSaveAs = dialog.WaitForResponse();

            if (!toSaveAs)
            {
                return(null);
            }

            string       path         = dialog.Filename;
            Encoding     encoding     = Encodings.GetEncoding(dialog.Encoding.CodePage);
            SubtitleType subtitleType = dialog.SubtitleType;
            NewlineType  newlineType  = dialog.NewlineType;
            TimingMode   timingMode   = Base.TimingMode;

            return(new FileProperties(path, encoding, subtitleType, timingMode, newlineType));
        }
コード例 #17
0
 private void saveAs()
 {
     if (slideEditController.ResourceProvider != null)
     {
         try
         {
             slideEditController.stopPlayingTimelines();
             FileSaveDialog fileDialog = new FileSaveDialog(MainWindow.Instance, wildcard: wildcard);
             fileDialog.showModal((result, path) =>
             {
                 if (result == NativeDialogResult.OK)
                 {
                     bool doSaveAs = true;
                     if (path.EndsWith(".show", StringComparison.InvariantCultureIgnoreCase)) //Special case for .show (folders) create a folder with the name of the project for the result to go into
                     {
                         String projectDir = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path));
                         path = Path.Combine(projectDir, Path.GetFileName(path));
                         if (Directory.Exists(projectDir))
                         {
                             doSaveAs = false;
                             MessageBox.show(String.Format("The folder for this project already exists at\n{0}\n\nWould you like to delete it and replace it with your new project?", projectDir), "Overwrite?", MessageBoxStyle.IconQuest | MessageBoxStyle.Yes | MessageBoxStyle.No, overwriteResult =>
                             {
                                 if (overwriteResult == MessageBoxStyle.Yes)
                                 {
                                     slideEditController.saveAs(path);
                                     updateCaption();
                                 }
                             });
                         }
                     }
                     if (doSaveAs)
                     {
                         slideEditController.saveAs(path);
                         updateCaption();
                     }
                 }
             });
         }
         catch (Exception ex)
         {
             MessageBox.show(String.Format("{0} saving the project. Message {1}.", ex.GetType().Name, ex.Message), "Project Save Error", MessageBoxStyle.IconError | MessageBoxStyle.Ok);
         }
     }
 }
コード例 #18
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (listCD.Count == 0)
            {
                MessageBox.Show("You don't have any item to be saved", "Saving Error", MessageBoxButtons.OK);
                return;
            }
            DialogResult save = FileSaveDialog.ShowDialog();

            if (save == DialogResult.OK)
            {
                string filename = FileSaveDialog.FileName;
                //tạo file hoặc nếu file tồn tại thì ghi đè lên tất cả nội dung cũ
                File.WriteAllText(filename, "");
                int count = 0;
                foreach (CDInformation cd in listCD)
                {
                    string songs = "";
                    //get songs
                    for (int i = 0; i < cd.Song.Count; i++)
                    {
                        songs += cd.Song[i];
                        if (i < cd.Song.Count - 1)
                        {
                            songs += "#";
                        }
                    }
                    //create string write to file
                    string CDInfo = string.Format("{0}~{1}~{2}~{3}~{4}~{5}",
                                                  cd.ID1,
                                                  cd.Album1,
                                                  cd.Singer1,
                                                  cd.Genre1,
                                                  cd.Duration,
                                                  songs);
                    if (count > 0)
                    {
                        File.AppendAllText(filename, Environment.NewLine);
                    }
                    File.AppendAllText(filename, CDInfo);
                    count++;
                }
            }
        }
コード例 #19
0
ファイル: SpHandlerCmd.cs プロジェクト: karthi1015/bim
        static string GetPathToFile()
        {
            string path = null;

            // Create a Revit task dialog to communicate information to the user.
            TaskDialog customTaskDialog = new TaskDialog("Shared Parameters");

            customTaskDialog.MainInstruction = "Please browse for a file to which  to export the shared parameters.";
            customTaskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;

            // Add commandLink options
            customTaskDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Browser");

            // Set common buttons
            customTaskDialog.CommonButtons = TaskDialogCommonButtons.Cancel;

            // Show the task dialog
            TaskDialogResult tResult = customTaskDialog.Show();

            if (TaskDialogResult.CommandLink1 == tResult)
            {
                FileSaveDialog fileSaveDialog = new FileSaveDialog("Text files|*.txt");

                //FileOpenDialog openFileDialog = new FileOpenDialog("Text files|*.txt");
                ItemSelectionDialogResult sbResult = fileSaveDialog.Show();
                if (sbResult == ItemSelectionDialogResult.Canceled)
                {
                    return(path);
                }
                else if (sbResult == ItemSelectionDialogResult.Confirmed)
                {
                    ModelPath modelPath = fileSaveDialog.GetSelectedModelPath();
                    path = ModelPathUtils.ConvertModelPathToUserVisiblePath(modelPath);
                }
            }
            else if (TaskDialogResult.Cancel == tResult)
            {
                return(path);
            }
            return(path);
        }
コード例 #20
0
        unsafe void reset_MouseButtonClick(Widget source, EventArgs e)
        {
            FileSaveDialog fileSave = new FileSaveDialog(MainWindow.Instance, "Save your audio file", wildcard: "Ogg Vorbis (*.ogg)|*.ogg");

            fileSave.showModal((result, file) =>
            {
                if (result == NativeDialogResult.OK)
                {
                    try
                    {
                        using (Stream destFile = File.Open(file, FileMode.Create, FileAccess.Write))
                        {
                            recordAudioController.save(destFile);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.Log.Error(ex.Message);
                    }
                }
            });
        }
コード例 #21
0
        public void initialize(StandaloneController standaloneController)
        {
            GUIManager guiManager = standaloneController.GUIManager;

            testImageAtlas = new TestImageAtlas();
            guiManager.addManagedDialog(testImageAtlas);

            testSoundRecord = new TestSoundRecord(standaloneController);
            guiManager.addManagedDialog(testSoundRecord);

            testTextureSceneView = new TestTextureSceneView(standaloneController.SceneViewController);
            guiManager.addManagedDialog(testTextureSceneView);

            standaloneController.TaskController.addTask(new CallbackTask("UnitTest.SaveFileDialog", "Test Save File", CommonResources.NoIcon, "Unit Test", 0, false, (item) =>
            {
                FileSaveDialog saveDialog = new FileSaveDialog(MainWindow.Instance, wildcard: "All Files|*");
                saveDialog.showModal((result, path) =>
                {
                    Log.Debug("Save dialog returned '{0}', path '{1}'", result, path);
                });
            }));

            //This is a test to make all the geometry in the scene one large object to test batching reduction, initial tests show huge improvement, only works under open gl.
            standaloneController.TaskController.addTask(new CallbackTask("UnitTest.StaticTest", "Static Test", CommonResources.NoIcon, "Unit Test", (item) =>
            {
                var scene        = standaloneController.MedicalController.CurrentScene;
                var sceneManager = scene.getSimElementManager("Ogre") as OgrePlugin.OgreSceneManager;
                var ogreScene    = sceneManager.SceneManager;
                var staticGeo    = ogreScene.createStaticGeometry("Test");
                staticGeo.addSceneNode(ogreScene.getRootSceneNode());
                ogreScene.getRootSceneNode().setVisible(false);
                staticGeo.build();
            }));

            standaloneController.TaskController.addTask(new MDIDialogOpenTask(testSoundRecord, "UnitTestPlugin.TestSoundRecord", "Sound Record", CommonResources.NoIcon, "Unit Test", true));
            standaloneController.TaskController.addTask(new MDIDialogOpenTask(testTextureSceneView, "UnitTestPlugin.TestTextureSceneView", "Texture Scene View", CommonResources.NoIcon, "Unit Test", true));
            standaloneController.TaskController.addTask(new MDIDialogOpenTask(testImageAtlas, "UnitTestPlugin.TestImageAtlas", "Image Atlas", CommonResources.NoIcon, "Unit Test", true));
        }
コード例 #22
0
        private void FileOpRename_Click(object sender, EventArgs e)
        {
            var selSpecPath = SelectedSpecificationPath;
            var dlg         = new FileSaveDialog(mRoot)
            {
                FileName = Path.GetFileNameWithoutExtension(selSpecPath)
            };

            if (dlg.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            var filePathNoExtn = Path.Combine(mRoot.UserSpecificationFolder, dlg.FileName);
            var filePath       = Path.ChangeExtension(filePathNoExtn, FileExtensions.MacroFileExtension);

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            File.Move(selSpecPath, filePath);
            RefreshSpecificationsList(SearchBox.Text.ToLower(CultureInfo.CurrentCulture));
        }
コード例 #23
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                // check user selection
                var uidoc              = commandData.Application.ActiveUIDocument;
                var doc                = uidoc.Document;
                var collection         = uidoc.Selection.GetElementIds();
                var hasFabricationPart = false;

                using (var trans = new Transaction(doc, "Change Spool Name"))
                {
                    trans.Start();

                    foreach (var elementId in collection)
                    {
                        var part = doc.GetElement(elementId) as FabricationPart;
                        if (part != null)
                        {
                            hasFabricationPart = true;
                            part.SpoolName     = "My Spool";
                        }
                    }

                    trans.Commit();
                }

                if (hasFabricationPart == false)
                {
                    message = "Select at least one fabrication part";
                    return(Result.Failed);
                }

                var callingFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                var saveAsDlg = new FileSaveDialog("PCF Files (*.pcf)|*.pcf");

                saveAsDlg.InitialFileName = callingFolder + "\\pcfExport";
                saveAsDlg.Title           = "Export To PCF";
                var result = saveAsDlg.Show();

                if (result == ItemSelectionDialogResult.Canceled)
                {
                    return(Result.Cancelled);
                }

                var fabParts = collection.ToList();

                string filename = ModelPathUtils.ConvertModelPathToUserVisiblePath(saveAsDlg.GetSelectedModelPath());

                FabricationUtils.ExportToPCF(doc, fabParts, filename);

                TaskDialog td = new TaskDialog("Export to PCF")
                {
                    MainIcon          = TaskDialogIcon.TaskDialogIconInformation,
                    TitleAutoPrefix   = false,
                    MainInstruction   = "Export to PCF was successful",
                    MainContent       = filename,
                    AllowCancellation = false,
                    CommonButtons     = TaskDialogCommonButtons.Ok
                };

                td.Show();

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
コード例 #24
0
 private void saveResults(NativeDialogResult result, String path, SendResult <String> resultCallback, FileSaveDialog dlg)
 {
     if (result == NativeDialogResult.OK)
     {
         String errorPrompt = null;
         if (!resultCallback(path, ref errorPrompt))
         {
             dlg.showModal((mResult, mPath) =>
             {
                 saveResults(mResult, mPath, resultCallback, dlg);
             });
         }
     }
 }
コード例 #25
0
 public static string Save()
 {
     return(FileSaveDialog.ShowDialog(IntPtr.Zero, "Save .wowvrc file", null, null, _filters, 0));
 }
コード例 #26
0
        int NativeInterfaces.IFileDialogEvents.OnFileOk(NativeInterfaces.IFileDialog pfd)
        {
            int hr = NativeConstants.S_OK;

            NativeInterfaces.IShellItem shellItem = null;

            if (NativeMethods.SUCCEEDED(hr))
            {
                hr = FileSaveDialog.GetResult(out shellItem);
            }

            if (!NativeMethods.SUCCEEDED(hr))
            {
                throw Marshal.GetExceptionForHR(hr);
            }

            string pathName = null;

            try
            {
                shellItem.GetDisplayName(NativeConstants.SIGDN.SIGDN_FILESYSPATH, out pathName);
            }

            finally
            {
                if (shellItem != null)
                {
                    try
                    {
                        Marshal.ReleaseComObject(shellItem);
                    }

                    catch (Exception)
                    {
                    }

                    shellItem = null;
                }
            }

            string pathNameResolved = ResolveName(pathName);

            NativeInterfaces.IOleWindow oleWindow = (NativeInterfaces.IOleWindow)pfd;

            try
            {
                IntPtr hWnd = IntPtr.Zero;
                oleWindow.GetWindow(out hWnd);
                Win32Window win32Window = new Win32Window(hWnd, oleWindow);

                // File name/path validation
                if (hr >= 0)
                {
                    try
                    {
                        // Verify that these can be parsed correctly
                        string fileName = Path.GetFileName(pathNameResolved);
                        string dirName  = Path.GetDirectoryName(pathNameResolved);
                    }

                    catch (Exception ex)
                    {
                        if (!FileDialogUICallbacks.ShowError(win32Window, pathNameResolved, ex))
                        {
                            throw;
                        }

                        hr = NativeConstants.S_FALSE;
                    }
                }

                if (hr >= 0)
                {
                    // Overwrite existing file
                    if (!OverwritePrompt)
                    {
                        hr = NativeConstants.S_OK;
                    }
                    else if (File.Exists(pathNameResolved))
                    {
                        FileOverwriteAction action = FileDialogUICallbacks.ShowOverwritePrompt(win32Window, pathNameResolved);

                        switch (action)
                        {
                        case FileOverwriteAction.Cancel:
                            hr = NativeConstants.S_FALSE;
                            break;

                        case FileOverwriteAction.Overwrite:
                            hr = NativeConstants.S_OK;
                            break;

                        default:
                            throw new InvalidEnumArgumentException();
                        }
                    }
                }
            }

            catch (Exception)
            {
            }

            finally
            {
                try
                {
                    Marshal.ReleaseComObject(oleWindow);
                }

                catch (Exception)
                {
                }

                oleWindow = null;
            }

            return(hr);
        }
コード例 #27
0
        [STAThread]         // <-- " If the attribute is not present, the application uses the multithreaded apartment model, which is not supported for Windows Forms."
        public static Int32 Main(String[] args)
        {
            Console.WriteLine("Now showing a folder browser dialog. Press [Enter] to continue.");
            _ = Console.ReadLine();

            // FolderBrowserDialog
            {
                String selectedDirectory = FolderBrowserDialog.ShowDialog(parentHWnd: IntPtr.Zero, title: "Select a folder...", initialDirectory: null);
                if (selectedDirectory != null)
                {
                    Console.WriteLine("Folder browser. Selected directory: \"{0}\".", selectedDirectory);
                }
                else
                {
                    Console.WriteLine("Folder browser. Cancelled.");
                }
            }

            Console.WriteLine("Now showing an open-file dialog to select multiple files (with multiple extension filters). Press [Enter] to continue.");
            _ = Console.ReadLine();

            // FileOpenDialog
            {
                Filter[] filters = new Filter[]
                {
                    new Filter("Images", "gif", "png", "jpg", "jpeg", "heic", "webp"),
                    new Filter("Videos", "mov", "wmv", "mp4", "mpeg", "mpg", "avi", "webm"),
                    new Filter("Audio", "mp3", "wma", "wav", "aac"),
                    new Filter("All files", "*"),
                };

                IReadOnlyList <String> fileNames = FileOpenDialog.ShowMultiSelectDialog(IntPtr.Zero, title: "Open multiple files...", initialDirectory: @"C:\Users\David\Music", defaultFileName: null, filters: filters, selectedFilterZeroBasedIndex: 2);
                if (fileNames != null)
                {
                    Console.WriteLine("Open file dialog. Selected files:");
                    foreach (String fileName in fileNames)
                    {
                        Console.WriteLine(fileName);
                    }
                }
                else
                {
                    Console.WriteLine("Open file dialog. Cancelled.");
                }
            }

            Console.WriteLine("Now showing an open-file dialog to select a single file (with a single extension filter). Press [Enter] to continue.");
            _ = Console.ReadLine();

            // FileOpenDialog
            {
                const String           windowsFormsFilter = @"Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";       // from https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filter(v=vs.110).aspx
                IReadOnlyList <Filter> filters            = Filter.ParseWindowsFormsFilter(windowsFormsFilter);

                IReadOnlyList <String> fileNames = FileOpenDialog.ShowMultiSelectDialog(IntPtr.Zero, title: "Open a single file...", initialDirectory: @"C:\Users\David\Music", defaultFileName: null, filters: filters, selectedFilterZeroBasedIndex: 2);
                if (fileNames != null)
                {
                    Console.WriteLine("Open file dialog. Selected files:");
                    foreach (String fileName in fileNames)
                    {
                        Console.WriteLine(fileName);
                    }
                }
                else
                {
                    Console.WriteLine("Open file dialog. Cancelled.");
                }
            }

            Console.WriteLine("Now showing an save-file dialog to save a single file (with multiple extension filters). Press [Enter] to continue.");
            _ = Console.ReadLine();

            // FileSaveDialog
            {
                Filter[] filters = new Filter[]
                {
                    new Filter("Images", "gif", "png", "jpg", "jpeg", "heic", "webp"),
                    new Filter("Videos", "mov", "wmv", "mp4", "mpeg", "mpg", "avi", "webm"),
                    new Filter("Audio", "mp3", "wma", "wav", "aac"),
                    new Filter("All files", "*"),
                };

                String initialDirectory = @"C:\Users\David\Music\Aerosmith\2006 - The Very Best Of\";
                String defaultFileName  = /*initialDirectory +*/ @"12 - Aerosmith - Dream On.mp3";

                String fileName = FileSaveDialog.ShowDialog(IntPtr.Zero, "Save a file...", initialDirectory, defaultFileName, filters, selectedFilterZeroBasedIndex: 2);
                if (fileName != null)
                {
                    Console.WriteLine("Save file dialog. Selected file: \"{0}\".", fileName);
                }
                else
                {
                    Console.WriteLine("Save file dialog. Cancelled.");
                }
            }

            Console.WriteLine("Shell file dialogs demo completed. Press [Enter] to exit.");
            _ = Console.ReadLine();

            return(0);
        }
コード例 #28
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                // check user selection
                var uidoc      = commandData.Application.ActiveUIDocument;
                var doc        = uidoc.Document;
                var elementIds = new HashSet <ElementId>();
                uidoc.Selection.GetElementIds().ToList().ForEach(x => elementIds.Add(x));

                var hasFabricationParts = false;
                foreach (var elementId in elementIds)
                {
                    var part = doc.GetElement(elementId) as FabricationPart;
                    if (part != null)
                    {
                        hasFabricationParts = true;
                        break;
                    }
                }

                if (hasFabricationParts == false)
                {
                    message = "Select at least one fabrication part";
                    return(Result.Failed);
                }

                var callingFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var saveAsDlg     = new FileSaveDialog("MAJ Files (*.maj)|*.maj");
                saveAsDlg.InitialFileName = callingFolder + "\\majExport";
                saveAsDlg.Title           = "Export To MAJ";
                var result = saveAsDlg.Show();

                if (result == ItemSelectionDialogResult.Canceled)
                {
                    return(Result.Cancelled);
                }

                string filename = ModelPathUtils.ConvertModelPathToUserVisiblePath(saveAsDlg.GetSelectedModelPath());

                ISet <ElementId> exported = FabricationPart.SaveAsFabricationJob(doc, elementIds, filename, new FabricationSaveJobOptions(true));
                if (exported.Count > 0)
                {
                    TaskDialog td = new TaskDialog("Export to MAJ")
                    {
                        MainIcon          = TaskDialogIcon.TaskDialogIconInformation,
                        TitleAutoPrefix   = false,
                        MainInstruction   = string.Concat("Export to MAJ was successful - ", exported.Count.ToString(), " Parts written"),
                        MainContent       = filename,
                        AllowCancellation = false,
                        CommonButtons     = TaskDialogCommonButtons.Ok
                    };

                    td.Show();
                }

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
コード例 #29
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public virtual Result Execute(ExternalCommandData commandData
                                      , ref string message, ElementSet elements)
        {
            try
            {
                // check user selection
                var uidoc = commandData.Application.ActiveUIDocument;
                var doc   = uidoc.Document;

                ISet <ElementId> parts = null;

                using (Transaction tr = new Transaction(doc, "Optimise Preselection"))
                {
                    tr.Start();
                    ICollection <ElementId> selElems = uidoc.Selection.GetElementIds();
                    if (selElems.Count > 0)
                    {
                        parts = new HashSet <ElementId>(selElems);
                    }

                    tr.Commit();
                }

                if (parts == null)
                {
                    MessageBox.Show("Select parts to export.");
                    return(Result.Failed);
                }

                var callingFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                var saveAsDlg = new FileSaveDialog("CSV Files (*.csv)|*.csv");

                saveAsDlg.InitialFileName = callingFolder + "\\geomExport";
                saveAsDlg.Title           = "Save Part Geometry As";
                var result = saveAsDlg.Show();

                if (result == ItemSelectionDialogResult.Canceled)
                {
                    return(Result.Cancelled);
                }

                string filename = ModelPathUtils.ConvertModelPathToUserVisiblePath(saveAsDlg.GetSelectedModelPath());
                string ext      = Path.GetExtension(filename);
                filename = Path.GetFileNameWithoutExtension(filename);

                int partcount = 1, exported = 0;

                foreach (ElementId eid in parts)
                {
                                // get all rods and kist with rods
                                FabricationPart part = doc.GetElement(eid) as FabricationPart;
                    if (part != null)
                    {
                        Options options = new Options();
                        options.DetailLevel = ViewDetailLevel.Coarse;

                        IList <Mesh> main = getMeshes(part.get_Geometry(options));
                        IList <Mesh> ins  = getMeshes(part.GetInsulationLiningGeometry());

                        int mlp = 0;
                        foreach (Mesh mesh in main)
                        {
                            String file = String.Concat(filename, partcount.ToString(), "-main-", (++mlp).ToString(), ext);
                            if (exportMesh(file, mesh))
                            {
                                exported++;
                            }
                        }

                        int ilp = 0;
                        foreach (Mesh mesh in ins)
                        {
                            String file = String.Concat(filename, partcount.ToString(), "-ins-", (++ilp).ToString(), ext);
                            if (exportMesh(file, mesh))
                            {
                                exported++;
                            }
                        }
                    }
                    partcount++;
                }

                String res         = (exported > 0) ? "Export was successful" : "Nothing was exported";
                String manywritten = String.Format("{0} Parts were exported", exported);

                TaskDialog td = new TaskDialog("Export Part Mesh Geometry")
                {
                    MainIcon          = TaskDialogIcon.TaskDialogIconInformation,
                    TitleAutoPrefix   = false,
                    MainInstruction   = res,
                    MainContent       = manywritten,
                    AllowCancellation = false,
                    CommonButtons     = TaskDialogCommonButtons.Ok
                };

                td.Show();

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
コード例 #30
0
        public static void Main(string[] args)
        {
            // FolderBrowserDialog
            {
                String selectedDirectory = FolderBrowserDialog.ShowDialog(IntPtr.Zero, "Title", null);
                if (selectedDirectory != null)
                {
                    Console.WriteLine("Folder browser. Selected directory: \"{0}\".", selectedDirectory);
                }
                else
                {
                    Console.WriteLine("Folder browser. Cancelled.");
                }
            }

            // FileOpenDialog
            {
                Filter[] filters = new Filter[]
                {
                    new Filter("Images", "gif", "png", "jpg", "jpeg", "heic", "webp"),
                    new Filter("Videos", "mov", "wmv", "mp4", "mpeg", "mpg", "avi", "webm"),
                    new Filter("Audio", "mp3", "wma", "wav", "aac"),
                    new Filter("All files", "*"),
                };

                String[] fileNames = FileOpenDialog.ShowMultiSelectDialog(IntPtr.Zero, "Title", @"C:\Users\David\Music", defaultFileName: null, filters: filters, selectedFilterZeroBasedIndex: 2);
                if (fileNames != null)
                {
                    Console.WriteLine("Open file dialog. Selected files:");
                    foreach (String fileName in fileNames)
                    {
                        Console.WriteLine(fileName);
                    }
                }
                else
                {
                    Console.WriteLine("Open file dialog. Cancelled.");
                }
            }

            // FileOpenDialog
            {
                const String windowsFormsFilter = @"Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";                 // from https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filter(v=vs.110).aspx
                Filter[]     filters            = Filter.ParseWindowsFormsFilter(windowsFormsFilter);

                String[] fileNames = FileOpenDialog.ShowMultiSelectDialog(IntPtr.Zero, "Title", @"C:\Users\David\Music", defaultFileName: null, filters: filters, selectedFilterZeroBasedIndex: 2);
                if (fileNames != null)
                {
                    Console.WriteLine("Open file dialog. Selected files:");
                    foreach (String fileName in fileNames)
                    {
                        Console.WriteLine(fileName);
                    }
                }
                else
                {
                    Console.WriteLine("Open file dialog. Cancelled.");
                }
            }

            // FileSaveDialog
            {
                Filter[] filters = new Filter[]
                {
                    new Filter("Images", "gif", "png", "jpg", "jpeg", "heic", "webp"),
                    new Filter("Videos", "mov", "wmv", "mp4", "mpeg", "mpg", "avi", "webm"),
                    new Filter("Audio", "mp3", "wma", "wav", "aac"),
                    new Filter("All files", "*"),
                };

                String initialDirectory = @"C:\Users\David\Music\Aerosmith\2006 - The Very Best Of\";
                String defaultFileName  = /*initialDirectory +*/ @"12 - Aerosmith - Dream On.mp3";

                String fileName = FileSaveDialog.ShowDialog(IntPtr.Zero, "Title", initialDirectory, defaultFileName, filters, selectedFilterZeroBasedIndex: 2);
                if (fileName != null)
                {
                    Console.WriteLine("Save file dialog. Selected file: \"{0}\".", fileName);
                }
                else
                {
                    Console.WriteLine("Save file dialog. Cancelled.");
                }
            }
        }