Exemple #1
0
        public static void SayMsg(string _title, string _msg)
        {
            TaskDialog thisDialog = new TaskDialog(_title);

            thisDialog.TitleAutoPrefix = false;
            thisDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
            thisDialog.MainInstruction = _msg;
            thisDialog.MainContent     = "";
            TaskDialogResult tResult = thisDialog.Show();
        }
 public static TaskDialogResult popupWarning(string instruction, TaskDialogCommonButtons commonButton, TaskDialogResult defButton)
 {
     TaskDialog tdlg = new TaskDialog(ReportResource.plrSettings);
      tdlg.MainInstruction = instruction;
      tdlg.AllowCancellation = true;
      tdlg.CommonButtons = commonButton;
      tdlg.DefaultButton = defButton;
      tdlg.TitleAutoPrefix = false;
      return tdlg.Show();
 }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try {
                string information = string.Empty;
                information += "Version: ";

                string revitVersion = commandData.Application.Application.VersionNumber;

                // get product version
                string productVersion = CommonUtils.Utils.ReadRegistryValue(revitVersion, "ProductVersion");
                productVersion = CommonUtils.Utils.GetProductVersion(productVersion);

                information += productVersion;

                // patch
                string productPatch = CommonUtils.Utils.ReadRegistryValue(revitVersion, "ProductPatch");
                if (!string.IsNullOrEmpty(productPatch) && !"-1".Equals(productPatch))
                {
                    information += "\nPatch: " + productPatch;
                }

                // product code
                string productCode = CommonUtils.Utils.ReadRegistryValue(revitVersion, "ProductCode");

                information += "\nCode: ";
                information += productCode;

                // Creates a Revit task dialog to communicate information to the user.
                TaskDialog mainDialog = new TaskDialog("About")
                {
                    MainContent = information
                };

                // Add commmandLink options to task dialog
                mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Inno revit tools website");

                // task dialog will show a Close button by default
                mainDialog.CommonButtons = TaskDialogCommonButtons.Close;
                mainDialog.DefaultButton = TaskDialogResult.Close;

                TaskDialogResult mainResult = mainDialog.Show();

                // If the user clicks the first command link, a simple Task Dialog
                if (TaskDialogResult.CommandLink1 == mainResult)
                {
                    System.Diagnostics.Process.Start(ConfigUtils.GetSetting(DefineUtils.Lm_Url_Frontend));
                }
            }
            catch (Exception ex) {
                //TaskDialog.Show("About", "Can't access information!");
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace.ToString());
            }

            return(Result.Succeeded);
        }
        /// <summary>
        /// Shows the TaskDialog.
        /// </summary>
        /// <returns>TaskDialogResult.</returns>
        public TaskDialogResult Show()
        {
            result = TaskDialogResult.Cancel;
            TaskDialogConfiguration nativeConfig = new TaskDialogConfiguration();

            nativeConfig.size            = (uint)Marshal.SizeOf(nativeConfig);
            nativeConfig.parentHandle    = hWndOwner;
            nativeConfig.commonButtons   = TaskDialogResult.Cancel;
            nativeConfig.content         = text;
            nativeConfig.windowTitle     = caption;
            nativeConfig.mainInstruction = instructionText;
            nativeConfig.taskDialogFlags = TaskDialogOptions.AllowCancel | TaskDialogOptions.ShowProgressBar | TaskDialogOptions.PositionRelativeToWindow | TaskDialogOptions.EnableHyperlinks;
            nativeConfig.callback        = new TaskDialogCallback(DialogProc);

            // Show the dialog.
            // NOTE: this is a BLOCKING call; the dialog proc callbacks
            // will be executed by the same thread as the
            // Show() call before the thread of execution
            // continues to the end of this method.
            showState = TaskDialogShowState.Showing;
            using (new EnableThemingInScope(true)) {     // Here is the way we use "vanilla" P/Invoke to call TaskDialogIndirect().
                TaskDialogIndirect(
                    nativeConfig,
                    out selectedButtonId,
                    IntPtr.Zero,
                    IntPtr.Zero);
            }
            showState = TaskDialogShowState.Closed;

            // Build and return dialog result to public API - leaving it
            // null after an exception is thrown is fine in this case
            if ((TaskDialogCommonButtonReturnId)selectedButtonId == TaskDialogCommonButtonReturnId.Ok)
            {
                result = TaskDialogResult.Ok;
            }

            // Reset progress bar.
            ProgressBarState = TaskDialogProgressBarState.Normal;
            ProgressBarValue = progressBarMinimum;

            // Free up strings.
            if (updatedStrings != null)
            {
                for (int i = 0; i < updatedStrings.Length; i++)
                {
                    if (updatedStrings[i] != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(updatedStrings[i]);
                        updatedStrings[i] = IntPtr.Zero;
                    }
                }
            }

            return(result);
        }
Exemple #5
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 Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData
                                                        , ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Autodesk.Revit.DB.Document doc = commandData.Application.ActiveUIDocument.Document;

            // get all PanelScheduleView instances in the Revit document.
            FilteredElementCollector fec = new FilteredElementCollector(doc);
            ElementClassFilter       PanelScheduleViewsAreWanted = new ElementClassFilter(typeof(PanelScheduleView));

            fec.WherePasses(PanelScheduleViewsAreWanted);
            List <Element> psViews = fec.ToElements() as List <Element>;

            bool noPanelScheduleInstance = true;

            foreach (Element element in psViews)
            {
                PanelScheduleView psView = element as PanelScheduleView;
                if (psView.IsPanelScheduleTemplate())
                {
                    // ignore the PanelScheduleView instance which is a template.
                    continue;
                }
                else
                {
                    noPanelScheduleInstance = false;
                }

                // choose what format export to, it can be CSV or HTML.
                TaskDialog alternativeDlg = new TaskDialog("Choose Format to export");
                alternativeDlg.MainContent       = "Click OK to export in .CSV format, Cancel to export in HTML format.";
                alternativeDlg.CommonButtons     = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel;
                alternativeDlg.AllowCancellation = true;
                TaskDialogResult exportToCSV = alternativeDlg.Show();

                Translator translator = TaskDialogResult.Cancel == exportToCSV ? new HTMLTranslator(psView) : new CSVTranslator(psView) as Translator;
                string     exported   = translator.Export();

                // open the file if export successfully.
                if (!string.IsNullOrEmpty(exported))
                {
                    System.Diagnostics.Process.Start(exported);
                }
            }

            if (noPanelScheduleInstance)
            {
                TaskDialog messageDlg = new TaskDialog("Warnning Message");
                messageDlg.MainIcon    = TaskDialogIcon.TaskDialogIconWarning;
                messageDlg.MainContent = "No panel schedule view is in the current document.";
                messageDlg.Show();
                return(Result.Cancelled);
            }

            return(Result.Succeeded);
        }
Exemple #6
0
        /// <summary>
        /// Close TaskDialog with a given TaskDialogResult
        /// </summary>
        /// <param name="closingResult">TaskDialogResult to return from the TaskDialog.Show() method</param>
        /// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception>
        public void Close(TaskDialogResult closingResult)
        {
            if (!NativeDialogShowing)
            {
                throw new InvalidOperationException(LocalizedMessages.TaskDialogCloseNonShowing);
            }

            nativeDialog.NativeClose(closingResult);
            // TaskDialog's own cleanup code -
            // which runs post show - will handle disposal of native dialog.
        }
Exemple #7
0
        /// <summary>
        ///     Shows the custom dialog described by the constructor and properties set by the caller, returns CustomDialogResult.
        /// </summary>
        /// <returns>
        ///     A CommonDialog.CustomDialogResult value.
        /// </returns>
        public TaskDialogResult Show()
        {
            var win = new TaskDialogWindow(this.ButtonsDisabledDelay)
            {
                tbCaption = { Text = this.Caption }
            };

            if (this.FooterText.Length > 0)
            {
                win.tbFooterText.Text = this.FooterText;

                if (this.FooterIcon != TaskDialogIcon.None)
                {
                    win.imgFooterIcon.Source = new BitmapImage(GetIcon(this.FooterIcon));
                }
                else
                {
                    win.imgFooterIcon.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                win.tbFooterText.Visibility  = Visibility.Collapsed;
                win.imgFooterIcon.Visibility = Visibility.Collapsed;
            }

            if (this.InstructionIcon == TaskDialogIcon.None)
            {
                win.imgInstructionIcon.Visibility = Visibility.Collapsed;
            }
            else
            {
                win.imgInstructionIcon.Source = new BitmapImage(GetIcon(this.InstructionIcon));
            }

            win.tbInstructionText.Text    = this.InstructionText;
            win.tbInstructionHeading.Text = this.InstructionHeading;

            if (this.AdditionalDetailsText.Length > 0)
            {
                win.tbAdditionalDetailsText.Text = this.AdditionalDetailsText;
            }
            else
            {
                win.expAdditionalDetails.Visibility = Visibility.Collapsed;
            }

            SetButtons(win);
            win.ShowInTaskbar = false;
            win.Topmost       = true;
            win.ShowDialog();
            _customDialogResult = win.TaskDialogResult;
            return(_customDialogResult);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LogEventArgs"/> class.
 /// </summary>
 /// <param name="taskDialogResult">The custom task dialog result.</param>
 /// <param name="instructionHeading">The instruction heading.</param>
 /// <param name="instructionText">The instruction text.</param>
 /// <param name="additionalDetailsText">The additional details text.</param>
 /// <param name="buttonsDisabledDelay">The buttons disabled delay.</param>
 /// <param name="userName">Name of the user.</param>
 /// <param name="exception">The exception.</param>
 public LogEventArgs(TaskDialogResult taskDialogResult, String instructionHeading, String instructionText, String additionalDetailsText, Int32 buttonsDisabledDelay, String userName, Exception exception)
 {
     _taskDialogResult      = taskDialogResult;
     _instructionHeading    = instructionHeading;
     _instructionText       = instructionText;
     _buttonsDisabledDelay  = buttonsDisabledDelay;
     _additionalDetailsText = additionalDetailsText;
     _userName    = userName;
     _exception   = exception;
     _dateCreated = DateTime.Now;
 }
Exemple #9
0
        /// <summary>
        /// Select elements in Revit to obtain the footprint roof lines.
        /// </summary>
        /// <returns>A curve array to hold the footprint roof lines.</returns>
        public CurveArray SelectFootPrint()
        {
            m_footPrint.Clear();
            while (true)
            {
                ElementSet es = new ElementSet();
                foreach (ElementId elementId in m_selection.GetElementIds())
                {
                    es.Insert(m_commandData.Application.ActiveUIDocument.Document.GetElement(elementId));
                }
                es.Clear();
                IList <Element> selectResult;
                try
                {
                    selectResult = m_selection.PickElementsByRectangle();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    break;
                }

                if (selectResult.Count != 0)
                {
                    foreach (Autodesk.Revit.DB.Element element in selectResult)
                    {
                        Wall wall = element as Wall;
                        if (wall != null)
                        {
                            LocationCurve wallCurve = wall.Location as LocationCurve;
                            m_footPrint.Append(wallCurve.Curve);
                            continue;
                        }

                        ModelCurve modelCurve = element as ModelCurve;
                        if (modelCurve != null)
                        {
                            m_footPrint.Append(modelCurve.GeometryCurve);
                        }
                    }
                    break;
                }
                else
                {
                    TaskDialogResult result = TaskDialog.Show("Warning", "You should select a curve loop, or a wall loop, or loops combination \r\nof walls and curves to create a footprint roof.", TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel);
                    if (result == TaskDialogResult.Cancel)
                    {
                        break;
                    }
                }
            }

            return(m_footPrint);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="result"></param>
        public TaskDialogStandardButton(
            TaskDialogResult result)
            : base()
        {
            if (!IsValidStandardButtonResult(result))
            {
                throw new ArgumentOutOfRangeException(nameof(result));
            }

            _result = result;
        }
Exemple #11
0
        /// <summary>
        /// Fatal error occurs, close the sample dialog directly
        /// </summary>
        /// <param name="errorMsg">
        /// the error hint shown to user
        /// </param>
        void m_document_FatalErrorEvent(string errorMsg)
        {
            // hang the sample and shown the error hint to users
            TaskDialogResult result = TaskDialog.Show(Properties.Resources.TXT_DialogTitle, errorMsg, TaskDialogCommonButtons.Ok, TaskDialogResult.Ok);

            // the user has read the hint and clicked the "OK" button, close the dialog
            if (TaskDialogResult.Ok == result)
            {
                this.Close();
            }
        }
Exemple #12
0
        public static bool ConfirmWriteToProtectedSectionOfRegistryOnVistaOrLater(string innerText)
        {
            string text = "In order to write " + innerText + ", Key Mapper needs to add to " +
                          "the protected section of your computer's registry. You may need to approve this action " +
                          "which will be performed by your Registry Editor.";

            TaskDialogResult result = FormsManager.ShowTaskDialog("Do you want to proceed?", text, "Key Mapper",
                                                                  TaskDialogButtons.Yes | TaskDialogButtons.No,
                                                                  TaskDialogIcon.SecurityShield);

            return(result == TaskDialogResult.Yes);
        }
Exemple #13
0
        private void Done(string TaskName)
        {
            TaskDialog td = new TaskDialog();
            TaskDialogStandardButtons button = TaskDialogStandardButtons.Ok;

            td.Icon            = TaskDialogStandardIcon.Information;
            td.StandardButtons = button;
            td.InstructionText = TaskName;
            td.Caption         = TaskName;
            td.Text            = Properties.Resources.Complete;
            TaskDialogResult res = td.Show();
        }
        /// <summary>
        /// Close TaskDialog with a given TaskDialogResult
        /// </summary>
        /// <param name="closingResult">TaskDialogResult to return from the TaskDialog.Show() method</param>
        /// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception>
        public void Close(TaskDialogResult closingResult)
        {
            if (!NativeDialogShowing)
            {
                throw new InvalidOperationException(
                          "Attempting to close a non-showing dialog.");
            }

            nativeDialog.NativeClose(closingResult);
            // TaskDialog's own cleanup code -
            // which runs post show - will handle disposal of native dialog.
        }
Exemple #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskDialog"/> class.
 /// </summary>
 /// <param name="caption">The caption.</param>
 /// <param name="instructionHeading">The instruction heading.</param>
 /// <param name="instructionText">The instruction text.</param>
 /// <param name="footerText">The footer text.</param>
 /// <param name="buttons">The buttons.</param>
 /// <param name="defaultButton">The default button.</param>
 /// <param name="instructionIcon">The instruction icon.</param>
 /// <param name="footerIcon">The footer icon.</param>
 /// <param name="buttonsDisabledDelay">The buttons disabled delay.</param>
 public TaskDialog(String caption, String instructionHeading, String instructionText, String footerText, TaskDialogButton buttons, TaskDialogResult defaultButton, TaskDialogIcon instructionIcon, TaskDialogIcon footerIcon, Int32 buttonsDisabledDelay = 0)
 {
     _caption                  = caption;
     _instructionHeading       = instructionHeading;
     _instructionText          = instructionText;
     _footerText               = footerText;
     _buttons                  = buttons;
     _defaultButton            = defaultButton;
     _instructionIcon          = instructionIcon;
     _footerIcon               = footerIcon;
     this.ButtonsDisabledDelay = buttonsDisabledDelay;
 }
Exemple #16
0
        private void ShowErrorMessage(string msg)
        {
            TaskDialog td = new TaskDialog()
            {
                StandardButtons = TaskDialogStandardButtons.Close,
                Caption         = "Error",
                InstructionText = msg,
                Icon            = TaskDialogStandardIcon.Error
            };

            TaskDialogResult res = td.Show();
        }
Exemple #17
0
 private void AskForParameterUpdates(Object sender, FileExportingEventArgs args)
 {
     TaskDialog td1 = new TaskDialog("Oppdatering av parameter før eksport");
     td1.MainInstruction = "Vil du oppdatere Schedule Mark?";
     td1.MainContent = "Slår sammen Partition og Rebar number og lagrer det til Schedule Number";
     td1.CommonButtons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;
         TaskDialogResult td1Result = td1.Show();
     if (td1Result == TaskDialogResult.Yes)
     {
         TaskDialog.Show("test", "Du trykka på Yes! Is read only: "+args.Document.IsReadOnly.ToString());
         ScheduleMarkUpdate.ScheduleMarkUpdater(args.Document);
     }
 }
Exemple #18
0
        private void UpdateResult(TaskDialogResult res)
        {
            if (res == null)
            {
                lbResult.Text = "Task Dialog Result";
                return;
            }

            StringBuilder strBldr = new StringBuilder();

            strBldr.AppendLine("Task Dialog Result");
            strBldr.AppendLine("Simple Result: " + res.Result.ToString());

            if (res.RadioButtonResult.HasValue)
            {
                strBldr.AppendLine("RadioButtonResult: " + res.RadioButtonResult.ToString());
            }
            else
            {
                strBldr.AppendLine("RadioButtonResult: <null>");
            }

            if (res.CommandButtonResult.HasValue)
            {
                strBldr.AppendLine("CommandButtonResult: " + res.CommandButtonResult.ToString());
            }
            else
            {
                strBldr.AppendLine("CommandButtonResult: <null>");
            }

            if (res.CustomButtonResult.HasValue)
            {
                strBldr.AppendLine("CustomButtonResult: " + res.CustomButtonResult.ToString());
            }
            else
            {
                strBldr.AppendLine("CustomButtonResult: <null>");
            }

            if (res.VerificationChecked.HasValue)
            {
                strBldr.Append("VerificationChecked: " + res.VerificationChecked.ToString());
            }
            else
            {
                strBldr.Append("VerificationChecked: <null>");
            }

            lbResult.Text = strBldr.ToString();
        }
        public void RevitDocumentChanged(object sender, DocumentChangedEventArgs args)
        {
            if (!IsShowEvent)
            {
                return;
            }

            // You can get the list of ids of element added/changed/modified.
            Document doc = args.GetDocument();

            ICollection <ElementId> idsAdded    = args.GetAddedElementIds();
            ICollection <ElementId> idsDeleted  = args.GetDeletedElementIds();
            ICollection <ElementId> idsModified = args.GetModifiedElementIds();

            //Add to parameter comment
            Element elem;

            // Put it in a string to show to the user.
            string msg = "Added: ";

            foreach (ElementId id in idsAdded)
            {
                elem = doc.GetElement(id);
                Parameter param = elem.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
                param.Set(DateTime.Today.ToString());
                msg += id.IntegerValue.ToString() + " ";
            }

            msg += "\nDeleted: ";
            foreach (ElementId id in idsDeleted)
            {
                msg += id.IntegerValue.ToString() + " ";
            }

            msg += "\nModified: ";
            foreach (ElementId id in idsModified)
            {
                msg += id.IntegerValue.ToString() + " ";
            }

            // Show a message to a user.
            TaskDialogResult res = default(TaskDialogResult);

            res = TaskDialog.Show("Revit UI Labs - Event", msg, TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel);

            // If the user chooses to cancel, show no more event.
            if (res == TaskDialogResult.Cancel)
            {
                IsShowEvent = false;
            }
        }
        private void DeleteButton_Click(object sender, EventArgs e)
        {
            ListView.CheckedListViewItemCollection checkedItems = ToolsListView.CheckedItems;

            if (checkedItems.Count < 1)
            {
                return;
            }

            TaskDialogResult result = TaskDialog.Show("Warning", "Are you sure you want to delete the selected tools?", TaskDialogCommonButtons.No | TaskDialogCommonButtons.Yes, TaskDialogResult.No);

            if (TaskDialogResult.No == result)
            {
                return;
            }
            else
            {
                foreach (ListViewItem item in checkedItems)
                {
                    string moduleName = item.Text;

                    TreePanelVisible(moduleName, false);
                    string dllModule = Path.Combine(m_modulePath, moduleName);

                    try
                    {
                        File.Delete(dllModule);
                    }
                    catch
                    {
                        TaskDialog.Show("Information", "Could not delete file: " + dllModule);
                    }

                    string addinModule = Path.GetFileNameWithoutExtension(dllModule);
                    addinModule += ".addin";
                    addinModule  = Path.Combine(m_modulePath, addinModule);

                    try
                    {
                        File.Delete(addinModule);
                    }
                    catch
                    {
                        TaskDialog.Show("Information", "Could not delete file: " + addinModule);
                    }
                }
                TreeViewFromArcadisRibbon();
            }

            GetModules(m_modulePath, m_up);
        }
        /// <summary>
        /// Closes the TaskDialog form.
        /// </summary>
        /// <param name="result">A TaskDialogResult that represents the result of the form.</param>
        public void Close(TaskDialogResult result)
        {
            if (_vdf == null)
            {
                throw new InvalidOperationException("Cannot invoke this method before the dialog is shown, or after it is closed.");
            }
            var button = new TaskDialogButton(result);

            _vdf.Tag = button;
            if (button.Result != TaskDialogResult.None)
            {
                _vdf.DialogResult = DialogResult.OK;
            }
        }
Exemple #22
0
        /// <summary>
        /// Shows a task dialog.
        /// </summary>
        /// <param name="sender">The owner of the dialog, or null.
        /// Should either be a window instance or the data context object of one.</param>
        /// <param name="options">A <see cref="T:TaskDialogOptions"/> config object.</param>
        /// <param name="callback">An optional callback method.</param>
        public void ShowTaskDialog(object sender, TaskDialogOptions options, Action <TaskDialogResult> callback)
        {
            if (options.Owner == null)
            {
                options.Owner = DialogHelper.TryGetOwnerFromSender(sender);
            }

            TaskDialogResult result = TaskDialog.Show(options);

            if (callback != null)
            {
                callback(result);
            }
        }
Exemple #23
0
        public void OnIdling(object sender, IdlingEventArgs e)
        {
            if (receiverActivated)
            {
                UIApplication uiapp = sender as UIApplication;
                Document      doc   = uiapp.ActiveUIDocument.Document;

                e.SetRaiseWithoutDelay();

                string value = RegistryKeyManager.GetRegistryKeyValue("RhinoOutgoing");
                if (!string.IsNullOrEmpty(value))
                {
                    if (value.ToLower() == "true")
                    {
                        TaskDialog dialog = new TaskDialog("Rhino Receiver");
                        dialog.MainInstruction = "Rhino Data";
                        dialog.MainContent     = "Analysis data from Rhino is being sent to Revit.";
                        dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Visualize Analysis Results");
                        dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Cancel");

                        TaskDialogResult result = dialog.Show();
                        if (result == TaskDialogResult.CommandLink1)
                        {
                            //AVF
                            string   tempDirectory = RegistryKeyManager.GetRegistryKeyValue("DivaTempDirectory");
                            string[] gridFiles     = Directory.GetFiles(tempDirectory, "*-AnalysisGrid.obj");
                            if (gridFiles.Length > 0)
                            {
                                List <ObjMesh> objMeshes   = new List <ObjMesh>();
                                bool           objImported = ObjImporter.ReadObjFile(gridFiles[0], out objMeshes);

                                string dataPath         = RegistryKeyManager.GetRegistryKeyValue("RhinoOutgoingPath");
                                AnalysisDataManager avf = new AnalysisDataManager(uiapp, objMeshes, dataPath);
                                if (avf.ReadResults())
                                {
                                    if (avf.CreateGeometry())
                                    {
                                        if (avf.VisualizeData())
                                        {
                                            MessageBox.Show("Result data from Rhino was successfully visualized.");
                                        }
                                    }
                                }
                            }
                        }
                        RegistryKeyManager.SetRegistryKeyValue("RhinoOutgoing", "False");
                    }
                }
            }
        }
Exemple #24
0
        public static void SayMsg(string _title, string _msg)
        {
            TaskDialog thisDialog = new TaskDialog(_title);

            thisDialog.TitleAutoPrefix = false;
            thisDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
            thisDialog.MainInstruction = _msg;
            thisDialog.MainContent     = "";
            TaskDialogResult tResult = thisDialog.Show();

            //FormMsgWPF NITV = new FormMsgWPF(0, true, true);
            //NITV.SetMsg(_msg, _title);
            //NITV.ShowDialog();
        }
Exemple #25
0
    {   /// <summary>
        ///
        /// </summary>
        /// <param name="commandData">传递给外部应用程序的对象,其中包含与命令相关的数据,如应用程序对象和活动视图。</param>
        /// <param name="message">可以由外部应用程序设置的消息,如果外部命令返回失败或取消,将显示该消息。</param>
        /// <param name="elements"></param>
        /// <returns></returns>
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Application app       = commandData.Application.Application;
            Document    activeDoc = commandData.Application.ActiveUIDocument.Document;

            TaskDialog mainDialog = new TaskDialog("Hello Reivt");

            mainDialog.MainInstruction = "Hello Revit";
            mainDialog.MainContent     = "这个例子可以演示一个外部命令是怎样加载到Revit用户界面的"
                                         + "它使用Revit任务对话框与用户交流信息\n"
                                         + "点击下面链接获取更多帮助";
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "关于Revit版本信息");
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "关于此文档的信息");
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "关于开发此Command的作者");
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink4, "关于软件日志");

            //设置常见按钮和默认按钮,如果不需要设置按钮,显示框不会展现按钮
            mainDialog.CommonButtons = TaskDialogCommonButtons.Close;
            mainDialog.DefaultButton = TaskDialogResult.Close;


            mainDialog.FooterText = "<a href=\"http://www.google.com \">"
                                    + "Click here for the Revit API Developer Center</a>";

            TaskDialogResult tResult = mainDialog.Show();

            if (TaskDialogResult.CommandLink1 == tResult)
            {
                TaskDialog dialog_CommandLink1 = new TaskDialog("Revit Build Information");
                dialog_CommandLink1.MainInstruction = "Revit Version Name is:" + "\t" + app.VersionName + "\n"
                                                      + "Revit Version Number is:" + "\t" + app.VersionNumber + "\n"
                                                      + "Revit Version Build is:" + "\t" + app.VersionBuild
                                                      + "Revit Username is" + "\t" + app.Username;
                dialog_CommandLink1.Show();
            }
            else if (TaskDialogResult.CommandLink2 == tResult)
            {
                TaskDialog.Show("Active Document Information", "Active document:" + activeDoc.Title + "\n"
                                + "Active view name:" + activeDoc.ActiveView.Name);
            }
            else if (TaskDialogResult.CommandLink3 == tResult)
            {
                TaskDialog.Show("Hello Baby", "This is just a test command XDDD");
            }
            else
            {
                TaskDialog.Show("日志", app.RecordingJournalFilename);
            }
            return(Result.Succeeded);
        }
Exemple #26
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Application app       = commandData.Application.Application;
            Document    activeDoc = commandData.Application.ActiveUIDocument.Document;

            // Creates a Revit task dialog to communicate information to the user.
            TaskDialog mainDialog = new TaskDialog("holo-blok");

            mainDialog.MainInstruction = "what's in the blok?";
            mainDialog.MainContent     =
                "We believe the act of building buildings should be more efficient."
                + "So we built So we built holo - blok to do just that";

            // Add commmandLink options to task dialog
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Contact");
            mainDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Build Version");

            // Set common buttons and default button. If no CommonButton or CommandLink is added,
            // task dialog will show a Close button by default
            mainDialog.CommonButtons = TaskDialogCommonButtons.Close;
            mainDialog.DefaultButton = TaskDialogResult.Close;

            // Set footer text. Footer text is usually used to link to the help document.
            //mainDialog.FooterText = "" + "Click here for the Revit API Developer Center";

            TaskDialogResult tResult = mainDialog.Show();

            // If the user clicks the first command link, a simple Task Dialog
            // with only a Close button shows information about the Revit installation.
            if (TaskDialogResult.CommandLink1 == tResult)
            {
                TaskDialog dialog_CommandLink1 = new TaskDialog("Contact");
                dialog_CommandLink1.MainInstruction =
                    "http://holo-blok.com/";

                dialog_CommandLink1.Show();
            }

            // If the user clicks the second command link, a simple Task Dialog
            // created by static method shows information about the active document
            else if (TaskDialogResult.CommandLink2 == tResult)
            {
                TaskDialog.Show("Build Version",
                                "Version 1.00" + "\n"
                                + "Complied Dec. 16 2019" + "\n"
                                + "*****@*****.**");
            }

            return(Result.Succeeded);
        }
Exemple #27
0
 private TaskDialogResult TDFamLoad(string path1, string famname1)
 {
   TaskDialog tdLoad = new TaskDialog("Предупреждение");
   tdLoad.MainIcon = TaskDialogIcon.TaskDialogIconError;
   tdLoad.Title = "Предупреждение";
   tdLoad.TitleAutoPrefix = false;
   tdLoad.AllowCancellation = false;
   tdLoad.MainInstruction = "Не загружено семейство:\n " + "[" + famname1 + "]" + "\n\n Загрузить ?";
   tdLoad.FooterText = path1.Substring(44);
   tdLoad.CommonButtons = TaskDialogCommonButtons.No | TaskDialogCommonButtons.Yes;
   tdLoad.DefaultButton = TaskDialogResult.Yes;
   TaskDialogResult tdRes = tdLoad.Show();
   return tdRes;
 }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // Get access to the top most objects. (we may not use them all in this specific lab.)
            _uiApp = commandData.Application;
            _uiDoc = _uiApp.ActiveUIDocument;

            // (1) create an instance of task dialog to set more options.

            TaskDialog houseDialog = new TaskDialog("Revit UI Labs - Create House Dialog");

            houseDialog.MainInstruction = "Create a house";
            houseDialog.MainContent     = "There are two options to create a house.";
            houseDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Interactive", "You will pick two corners of rectangular footprint of a house, and choose where you want to add a front door.");
            houseDialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Automatic", "This is will automatically place a house with a default settings.");
            houseDialog.CommonButtons = TaskDialogCommonButtons.Cancel;
            houseDialog.DefaultButton = TaskDialogResult.CommandLink1;

            // Show the dialog to the user.

            TaskDialogResult res = houseDialog.Show();

            //TaskDialog.Show( "Create house dialog", "The last action was: " + res.ToString());

            // (2) pause the result and create a house with the method that use has chosen.
            //
            // Create a house interactively.
            if (res == TaskDialogResult.CommandLink1)
            {
                UICreateHouse.CreateHouseInteractive(_uiDoc);
                return(Result.Succeeded);
            }

            // Create a house automatically with the default settings.
            if (res == TaskDialogResult.CommandLink2)
            {
                IntroCs.ModelCreationExport.CreateHouse(_uiDoc.Document);
                return(Result.Succeeded);
            }

            // Request canceled.
            if (res == TaskDialogResult.Cancel)
            {
                return(Result.Cancelled);
            }
            return(Result.Succeeded);
        }
        /// <summary>
        /// Check for file registration if running Windows 7 for Taskbar support
        /// </summary>
        public static void CheckFileRegistration()
        {
            bool registered = false;

            try
            {
                RegistryKey appCommand = Registry.ClassesRoot.OpenSubKey(Path.Combine(Application.ProductName, @"shell\Open\Command"));
                if (appCommand != null)
                {
                    string value = appCommand.GetValue("", null) as string;

                    if (string.IsNullOrEmpty(value)) // !value.Contains(Application.ExecutablePath) is quite annoying
                    {
                        registered = false;
                    }
                    else
                    {
                        registered = true;
                    }
                }
            }
            catch (Exception ex)
            {
                DebugHelper.WriteException(ex);
            }
            finally
            {
                // Let the user know
                if (!registered)
                {
                    td                 = new TaskDialog();
                    td.Caption         = GetProductName();
                    td.Text            = "File types are not registered";
                    td.InstructionText = "ZScreen needs to register image files as associated files to properly execute the Taskbar related features.";
                    td.Icon            = TaskDialogStandardIcon.Information;
                    td.Cancelable      = true;

                    TaskDialogCommandLink tdclRegister = new TaskDialogCommandLink("registerButton", "Register file type for this application",
                                                                                   "Register image/text files with this application to run ZScreen correctly.");
                    tdclRegister.Click += new EventHandler(btnRegisterWin7_Click);
                    // Show UAC shield as this task requires elevation
                    tdclRegister.UseElevationIcon = true;

                    td.Controls.Add(tdclRegister);

                    TaskDialogResult tdr = td.Show();
                }
            }
        }
Exemple #30
0
        private bool UserDecidedToUpdateGeometry(out bool deleteExisting)
        {
            TaskDialog decide = new TaskDialog("Pipe Data Received");

            decide.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Replace Objects",
                                  "Objects in the scene will be deleted and replaced with the new objects");
            decide.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Update Geometry",
                                  "The objects will not be deleted, but their geometry will be updated.");
            decide.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "Append New Geometry",
                                  "New geometry will be added to the document without changing the existing geometry.");
            TaskDialogResult result = decide.Show();

            deleteExisting = result == TaskDialogResult.CommandLink1;
            return(result == TaskDialogResult.CommandLink2);
        }
        /// <summary>
        /// Close TaskDialog with a given TaskDialogResult
        /// </summary>
        /// <param name="result">TaskDialogResult to return from the Show() method</param>
        /// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception>
        public void Close(TaskDialogResult result)
        {
            if (!NativeDialogShowing)
            {
                throw new InvalidOperationException();
            }
            showState = TaskDialogShowState.Closing;
            int id = (int)TaskDialogCommonButtonReturnId.Cancel;

            if (result == TaskDialogResult.Ok)
            {
                id = (int)TaskDialogCommonButtonReturnId.Ok;
            }
            SendMessageHelper(TaskDialogMessage.ClickButton, id, 0);
        }
 /// <summary>
 /// Closes the TaskDialog form.
 /// </summary>
 /// <param name="result">A TaskDialogResult that represents the result of the form.</param>
 public void Close(TaskDialogResult result)
 {
     if (_tdf == null)
     {
         throw new InvalidOperationException("Cannot invoke this method before the dialog is shown, or after it is closed.");
     }
     var button = new TaskDialogButton(result);
     _tdf.Tag = button;
     if (button.Result != TaskDialogResult.None)
     {
         _tdf.DialogResult = DialogResult.OK;
     }
 }
Exemple #33
0
        /// <summary>
        /// Displays a TaskDialog-based error dialog with the error icon.
        /// </summary>
        /// <param name="title">The dialog's title.</param>
        /// <param name="text">The dialog's body.</param>
        /// <returns>TaskDialogResult.</returns>
        public TaskDialogResult ShowError( string title, string text )
        {
            result = TaskDialogResult.No;
            TaskDialogConfiguration nativeConfig = new TaskDialogConfiguration();
            Icon = TaskDialogStandardIcon.Error;

            nativeConfig.size = (uint) Marshal.SizeOf( nativeConfig );
            nativeConfig.parentHandle = hWndOwner;
            nativeConfig.commonButtons = TaskDialogResult.Ok;
            nativeConfig.content = text;
            nativeConfig.windowTitle = title;
            nativeConfig.mainInstruction = instructionText;
            nativeConfig.taskDialogFlags = TaskDialogOptions.AllowCancel | TaskDialogOptions.PositionRelativeToWindow;
            nativeConfig.callback = new TaskDialogCallback( DialogProc );

            showState = TaskDialogShowState.Showing;
            using ( new EnableThemingInScope( true ) ) { // Here is the way we use "vanilla" P/Invoke to call TaskDialogIndirect().
                TaskDialogIndirect(
                    nativeConfig,
                    out selectedButtonId,
                    IntPtr.Zero,
                    IntPtr.Zero );
            }
            showState = TaskDialogShowState.Closed;

            if ( (TaskDialogCommonButtonReturnId) selectedButtonId == TaskDialogCommonButtonReturnId.Ok ) {
                result = TaskDialogResult.Ok;
            }

            // Free up strings.
            if ( updatedStrings != null ) {
                for ( int i = 0; i < updatedStrings.Length; i++ ) {
                    if ( updatedStrings[i] != IntPtr.Zero ) {
                        Marshal.FreeHGlobal( updatedStrings[i] );
                        updatedStrings[i] = IntPtr.Zero;
                    }
                }
            }

            return result;
        }
 public void ClickCommonButton(TaskDialogResult buttonID) => ClickButton((int)buttonID);
Exemple #35
0
 /// <summary>
 /// Close TaskDialog with a given TaskDialogResult
 /// </summary>
 /// <param name="result">TaskDialogResult to return from the Show() method</param>
 /// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception>
 public void Close( TaskDialogResult result )
 {
     if ( !NativeDialogShowing ) throw new InvalidOperationException();
     showState = TaskDialogShowState.Closing;
     int id = (int) TaskDialogCommonButtonReturnId.Cancel;
     if ( result == TaskDialogResult.Ok ) id = (int) TaskDialogCommonButtonReturnId.Ok;
     SendMessageHelper( TaskDialogMessage.ClickButton, id, 0 );
 }
Exemple #36
0
        /// <summary>
        /// Shows the TaskDialog.
        /// </summary>
        /// <returns>TaskDialogResult.</returns>
        public TaskDialogResult Show()
        {
            result = TaskDialogResult.Cancel;
            TaskDialogConfiguration nativeConfig = new TaskDialogConfiguration();

            nativeConfig.size = (uint) Marshal.SizeOf( nativeConfig );
            nativeConfig.parentHandle = hWndOwner;
            nativeConfig.commonButtons = TaskDialogResult.Cancel;
            nativeConfig.content = text;
            nativeConfig.windowTitle = caption;
            nativeConfig.mainInstruction = instructionText;
            nativeConfig.taskDialogFlags = TaskDialogOptions.AllowCancel | TaskDialogOptions.ShowProgressBar | TaskDialogOptions.PositionRelativeToWindow | TaskDialogOptions.EnableHyperlinks;
            nativeConfig.callback = new TaskDialogCallback( DialogProc );

            // Show the dialog.
            // NOTE: this is a BLOCKING call; the dialog proc callbacks
            // will be executed by the same thread as the
            // Show() call before the thread of execution
            // continues to the end of this method.
            showState = TaskDialogShowState.Showing;
            using ( new EnableThemingInScope( true ) ) { // Here is the way we use "vanilla" P/Invoke to call TaskDialogIndirect().
                TaskDialogIndirect(
                    nativeConfig,
                    out selectedButtonId,
                    IntPtr.Zero,
                    IntPtr.Zero );
            }
            showState = TaskDialogShowState.Closed;

            // Build and return dialog result to public API - leaving it
            // null after an exception is thrown is fine in this case
            if ( (TaskDialogCommonButtonReturnId) selectedButtonId == TaskDialogCommonButtonReturnId.Ok ) {
                result = TaskDialogResult.Ok;
            }

            // Reset progress bar.
            ProgressBarState = TaskDialogProgressBarState.Normal;
            ProgressBarValue = progressBarMinimum;

            // Free up strings.
            if ( updatedStrings != null ) {
                for ( int i = 0; i < updatedStrings.Length; i++ ) {
                    if ( updatedStrings[i] != IntPtr.Zero ) {
                        Marshal.FreeHGlobal( updatedStrings[i] );
                        updatedStrings[i] = IntPtr.Zero;
                    }
                }
            }

            return result;
        }
 /// <summary>
 /// Initializes the new instance of the TaskDialogButton.
 /// </summary>
 /// <param name="tresult">Determines the value returned to the parent form when the button is clicked.</param>
 /// <param name="text">The custom text shown on the button.</param>
 /// <param name="showElevationIcon">Determines whether to show the elevation icon (shield).</param>
 public TaskDialogButton(TaskDialogResult tresult, string text, bool showElevationIcon)
 {
     _useCustomText = true;
     _text = text;
     _result = tresult;
     _showElevationIcon = showElevationIcon;
     _isEnabled = true;
 }
        // The new task dialog does not support the existing
        // Win32 functions for closing (e.g. EndDialog()); instead,
        // a "click button" message is sent. In this case, we're
        // abstracting out to say that the TaskDialog consumer can
        // simply call "Close" and we'll "click" the cancel button.
        // Note that the cancel button doesn't actually
        // have to exist for this to work.
        internal void NativeClose(TaskDialogResult result)
        {
            showState = DialogShowState.Closing;

            int id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDCANCEL;

            if(result == TaskDialogResult.Close)
                id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDCLOSE;
            else if(result == TaskDialogResult.CustomButtonClicked)
                id = DialogsDefaults.MinimumDialogControlId; // custom buttons
            else if(result == TaskDialogResult.No)
                id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDNO;
            else if(result == TaskDialogResult.Ok)
                id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDOK;
            else if(result == TaskDialogResult.Retry)
                id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDRETRY;
            else if(result == TaskDialogResult.Yes)
                id = (int)TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDYES;

            SendMessageHelper(TaskDialogNativeMethods.TASKDIALOG_MESSAGES.TDM_CLICK_BUTTON, id, 0);
        }
 /// <summary>
 /// Initializes the new instance of the TaskDialogButton.
 /// </summary>
 /// <param name="result">Determines the value returned to the parent form when the button is clicked.</param>
 /// <param name="showElevationIcon">Determines whether to show the elevation icon (shield).</param>
 public TaskDialogButton(TaskDialogResult result, bool showElevationIcon)
 {
     _result = result;
     _showElevationIcon = showElevationIcon;
     _isEnabled = true;
 }
 /// <summary>
 /// Displays a task dialog with specified text, title, buttons, icon, and default button.
 /// </summary>
 /// <param name="text">The text to display in the task dialog.</param>
 /// <param name="title">The text to display in the title bar of the task dialog.</param>
 /// <param name="buttons">One of the TaskDialogCommonButtons values that specifies which buttons to display in the task dialog.</param>
 /// <param name="icon">One of the TaskDialogIcon values that specifies which icon to display in the task dialog.</param>
 /// <param name="defaultButton">TaskDialogResult value that specifies the default button for the task dialog.</param>
 /// <returns>One of the TaskDialogResult values.</returns>
 public static TaskDialogResult Show(string text, string title, TaskDialogCommonButtons buttons, TaskDialogIcon icon, TaskDialogResult defaultButton)
 {
     return Show(DefaultOwnerWindow, text, title, buttons, icon, defaultButton);
 }
 /// <summary>
 /// Displays a task dialog in front of the specified window and with specified text, title, buttons, icon, and default button.
 /// </summary>
 /// <param name="owner">A window that will own the modal dialog box.</param>
 /// <param name="text">The text to display in the task dialog.</param>
 /// <param name="title">The text to display in the title bar of the task dialog.</param>
 /// <param name="buttons">One of the TaskDialogCommonButtons values that specifies which buttons to display in the task dialog.</param>
 /// <param name="icon">One of the TaskDialogIcon values that specifies which icon to display in the task dialog.</param>
 /// <param name="defaultButton">TaskDialogResult value that specifies the default button for the task dialog.</param>
 /// <returns>One of the TaskDialogResult values.</returns>
 public static TaskDialogResult Show(Window owner, string text, string title, TaskDialogCommonButtons buttons, TaskDialogIcon icon, TaskDialogResult defaultButton)
 {
     TaskDialogWindow td = new TaskDialogWindow(null, false)
     {
         Owner = owner,
         WindowTitle = title,
         MainIcon = icon,
         ContentText = text,
         CommonButtons = buttons,
         DefaultButton = defaultButton,
     };
     td.ShowDialog();
     return (TaskDialogResult)td.Tag;
 }
 /// <summary>
 /// Enables or disables a button of an active task dialog.
 /// </summary>
 /// <param name="buttonID"></param>
 /// <param name="enable"></param>
 public void SetCommonButtonEnabled(TaskDialogResult buttonID, bool enable) => SetButtonEnabled((int)buttonID, enable);
 /// <summary>
 /// Initializes the new instance of the TaskDialogButton.
 /// </summary>
 /// <param name="text">The custom text shown on the button.</param>
 /// <param name="click">Occurs when the button is clicked, but before the TaskDialog form is closed.</param>
 public TaskDialogButton(string text, EventHandler click)
 {
     _useCustomText = true;
     _text = text;
     _result = TaskDialogResult.None;
     this.Click += click;
     _isEnabled = true;
 }
 /// <summary>
 /// Initializes the new instance of the TaskDialogButton.
 /// </summary>
 /// <param name="text">The custom text shown on the button.</param>
 /// <param name="click">Occurs when the button is clicked, but before the TaskDialog form is closed.</param>
 /// <param name="showElevationIcon">Determines whether to show the elevation icon (shield).</param>
 public TaskDialogButton(string text, EventHandler click, bool showElevationIcon)
 {
     _useCustomText = true;
     _text = text;
     _result = TaskDialogResult.None;
     this.Click += click;
     _showElevationIcon = showElevationIcon;
     _isEnabled = true;
 }
 /// <summary>
 /// Initializes the new instance of the TaskDialogButton.
 /// </summary>
 /// <param name="taskDialogResult">Determines the value returned to the parent form when the button is clicked.</param>
 /// <param name="text">The custom text shown on the button.</param>
 public TaskDialogButton(TaskDialogResult taskDialogResult, string text)
 {
     _useCustomText = true;
     _text = text;
     _result = taskDialogResult;
     _isEnabled = true;
 }
Exemple #46
0
 /// <summary>
 /// TaskDialogResult 値を Result 値に変換する。
 /// </summary>
 /// <param name="src">TaskDialogResult 値。</param>
 /// <returns>Result 値。</returns>
 private static Result Convert(TaskDialogResult src)
 {
     switch (src)
     {
     case TaskDialogResult.Ok: return Result.Ok;
     case TaskDialogResult.Cancel: return Result.Cancel;
     }
     return Result.None;
 }
 /// <summary>
 /// Initializes the new instance of the TaskDialogButton.
 /// </summary>
 /// <param name="result">Determines the value returned to the parent form when the button is clicked.</param>
 public TaskDialogButton(TaskDialogResult result)
 {
     _result = result;
     _isEnabled = true;
 }
        /// <summary>
        /// Shows the dialog. After the dialog is created, the <see cref="Opened"/>
        /// event occurs which allows to customize the dialog. When the dialog is closed, the
        /// <see cref="Closing"/> event occurs.
        /// 
        /// Starting with the <see cref="Opened"/>, you can call methods on the active task dialog
        /// to update its state until the <see cref="Closing"/> event occurs.
        /// </summary>
        /// <param name="owner">The window handle of the owner</param>
        public void Show(IntPtr hwndOwner)
        {
            // Recursive Show() is not possible because we would use the same callback delegate..
            if (currentOwnerHwnd.HasValue)
                throw new InvalidOperationException("Cannot recursively show the same task dialog instance.");

            CheckButtonConfig();
            PrepareButtonConfig(out currentCustomButtons, out currentRadioButtons);

            currentOwnerHwnd = hwndOwner;
            TaskDialogConfig config;
            CreateConfig(out config);
            try
            {
                int ret = 0;
                int resultButtonID, resultRadioButtonID;
                try
                {
                    ret = TaskDialogIndirect(ref config, out resultButtonID, out resultRadioButtonID,
                        out resultVerificationFlagChecked);
                }
                // Only catch exceptions if the hWnd of the task dialog is not set, otherwise the exception
                // must have occured in the callback.
                // Note: If a exception occurs here when hwndDialog is not 0, it means the TaskDialogIndirect
                // run the event loop and called a WndProc e.g. from a window, whose event handler threw an 
                // exception. In that case we cannot catch and marshal it to a HResult, so the CLR will 
                // manipulate the managed stack so that it doesn't contain the transition to and from native
                // code. However, the TaskDialog still calls our TaskDialogCallbackProc (by dispatching
                // messages to the WndProc) when the current event handler from WndProc returns, but the GC might
                // already have collected the delegate to it which will cause a NRE/AccessViolation.

                // This is OK because the same issue occurs when using a Messagebox with WPF or WinForms:
                // If do MessageBox.Show() wrapped in a try/catch on a button click, and before calling .Show()
                // create and start a timer which stops and throws an exception on its Tick event,
                // the application will crash with an AccessViolationException as soon as you close the MessageBox.
                catch (Exception ex) when (hwndDialog == IntPtr.Zero &&
                    (ex is DllNotFoundException || ex is EntryPointNotFoundException))
                {
                    // Show a regular messagebox instead. This should only happen if we debug and for some
                    // reason the VS host process doesn't use our manifest.
                    StringBuilder msgContent = new StringBuilder();
                    if (MainInstruction != null)
                        msgContent.Append(MainInstruction + "\n\n");
                    if (Content != null)
                        msgContent.Append(Content + "\n\n");
                    if (ExpandedInformation != null)
                        msgContent.Append(ExpandedInformation + "\n\n");
                    MessageBox.Show(msgContent.ToString(), Title, MessageBoxButton.OK);

                    resultButtonID = (int)TaskDialogResult.Ok;
                    resultRadioButtonID = 0;
                }
                // Marshal.ThrowExceptionForHR will use the IErrorInfo on the current thread if it exists, ignoring
                // the error code. Therefore we only call it if the HResult is not OK to avoid incorrect
                // exceptions being thrown.
                // However, if the HResult indicates an error we need to use the IErrorInfo because the exception might
                // be a managed exception thorwn in the callback and translated to a HResult by
                // Marshal.GetHRForException(Exception).
                if (ret != HResultOk)
                    Marshal.ThrowExceptionForHR(ret);

                // Set the result fields
                CustomButton myResultCustomButton = null;
                if (currentCustomButtons?.TryGetValue(resultButtonID, out myResultCustomButton) == true)
                {
                    resultCustomButton = myResultCustomButton;
                    resultCommonButtonID = 0;
                }
                else
                {
                    resultCommonButtonID = (TaskDialogResult)resultButtonID;
                    resultCustomButton = null;
                }

                // Note that even if we have radio buttons, it could be that the user didn't select one.
                if (!(currentRadioButtons?.TryGetValue(resultRadioButtonID, out resultRadioButton) == true))
                    resultRadioButton = null;

            }
            finally
            {
                // Clear the handles and free the memory.
                currentOwnerHwnd = null;
                DisposeConfig(ref config);

                ClearButtonConfig(currentCustomButtons, currentRadioButtons);
                currentCustomButtons = null;
                currentRadioButtons = null;

                // We need to ensure the callback delegate is not garbage-collected as long as TaskDialogIndirect
                // doesn't return, by calling GC.KeepAlive().
                // 
                // This is not an exaggeration, as the comment for GC.KeepAlive() says the following:
                // The JIT is very aggressive about keeping an 
                // object's lifetime to as small a window as possible, to the point
                // where a 'this' pointer isn't considered live in an instance method
                // unless you read a value from the instance.
                GC.KeepAlive(callbackProcDelegate);
            }
        }
Exemple #49
0
        /// <summary>
        /// Close TaskDialog with a given TaskDialogResult
        /// </summary>
        /// <param name="closingResult">TaskDialogResult to return from the TaskDialog.Show() method</param>
        /// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception>
        public void Close(TaskDialogResult closingResult)
        {
            if (!NativeDialogShowing)
            {
                throw new InvalidOperationException(LocalizedMessages.TaskDialogCloseNonShowing);
            }

            nativeDialog.NativeClose(closingResult);
            // TaskDialog's own cleanup code -
            // which runs post show - will handle disposal of native dialog.
        }
        // The new task dialog does not support the existing 
        // Win32 functions for closing (e.g. EndDialog()); instead,
        // a "click button" message is sent. In this case, we're 
        // abstracting out to say that the TaskDialog consumer can
        // simply call "Close" and we'll "click" the cancel button. 
        // Note that the cancel button doesn't actually
        // have to exist for this to work.
        internal void NativeClose(TaskDialogResult result)
        {
            ShowState = DialogShowState.Closing;

            int id;
            switch (result)
            {
                case TaskDialogResult.Close:
                    id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Close;
                    break;
                case TaskDialogResult.CustomButtonClicked:
                    id = DialogsDefaults.MinimumDialogControlId; // custom buttons
                    break;
                case TaskDialogResult.No:
                    id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.No;
                    break;
                case TaskDialogResult.Ok:
                    id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Ok;
                    break;
                case TaskDialogResult.Retry:
                    id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Retry;
                    break;
                case TaskDialogResult.Yes:
                    id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Yes;
                    break;
                default:
                    id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Cancel;
                    break;
            }

            SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.ClickButton, id, 0);
        }
 /// <summary>
 /// Specifies whether the command button icon of an active task dialog should be changed
 /// to the UAC shield symbol.
 /// </summary>
 /// <param name="buttonID"></param>
 /// <param name="requiresElevation"></param>
 public void SetButtonElevationRequiredState(TaskDialogResult buttonID, bool requiresElevation) =>
     SetButtonElevationRequiredState((int)buttonID, requiresElevation);
        /// <summary>
        /// Close TaskDialog with a given TaskDialogResult
        /// </summary>
        /// <param name="closingResult">TaskDialogResult to return from the TaskDialog.Show() method</param>
        /// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception>
        public void Close(TaskDialogResult closingResult)
        {
            if (!NativeDialogShowing)
                throw new InvalidOperationException(
                    "Attempting to close a non-showing dialog.");

            nativeDialog.NativeClose(closingResult);
            // TaskDialog's own cleanup code -
            // which runs post show - will handle disposal of native dialog.
        }
 public CommonButtonClickedEventArgs(TaskDialogResult buttonID)
 {
     ButtonID = buttonID;
 }