public static int Run(NSAlert view, Control parent) { int ret; if (parent != null) { var window = parent.ControlObject as NSWindow; if (window == null && parent.ControlObject is NSView) { window = ((NSView)parent.ControlObject).Window; } if (window == null || !view.RespondsToSelector(new Selector("beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:"))) { ret = (int)view.RunModal(); } else { ret = 0; NSApplication.SharedApplication.InvokeOnMainThread(delegate { view.BeginSheet(window, new MacModal(), new Selector("alertDidEnd:returnCode:contextInfo:"), IntPtr.Zero); ret = (int)NSApplication.SharedApplication.RunModalForWindow(window); }); } } else { ret = (int)view.RunModal(); } return(ret); }
partial void ReadStat(Foundation.NSObject sender) { string res; Stat stat; LibraryImport.read_stat_(StatPath.StringValue, out res); if (res == null) { Alert.MessageText = "Не найден файл \"" + StatPath.StringValue + "\"."; Alert.RunModal(); return; } // Директория с загружаемым файлом string TmpFileLocDir = Path.GetDirectoryName(StatPath.StringValue); try { stat = new Stat(res, TmpFileLocDir); } catch (Exception) { LibraryImport.read_stat_(StatPath.StringValue, out res); stat = new Stat(res, TmpFileLocDir); } //--- Save files ---// string TmpDirPath = StatDir.StatDirPath + stat.GetHashCode(); Directory.CreateDirectory(TmpDirPath); var creationTime = DateTime.Now; FileStream file = File.Create(TmpDirPath + "/stat.json"); file.Write(new UTF8Encoding(true).GetBytes(res)); file.Close(); foreach (var inter in stat.Info.inter) { if (!File.Exists(TmpDirPath + '/' + inter.id.pname)) { try { if (File.Exists(TmpFileLocDir + '/' + inter.id.pname)) { File.Copy(TmpFileLocDir + '/' + inter.id.pname, TmpDirPath + '/' + inter.id.pname); } } catch (Exception) { Console.WriteLine("Could not copy file '" + inter.id.pname + "'"); } } } AddStatToList(stat, creationTime); }
partial void btnTestStudent(Foundation.NSObject sender) { var student = new Student(); student.FirstName = txtName.StringValue; var gp = student.ComputeGradeAverage(); var experiment = new ScienceExperiment(); experiment.MaximumScore = 20; experiment.Score = 1; experiment.Conclusion = "Great"; var englishtest = new EnglishPaper(); englishtest.Score = 12; englishtest.MaximumScore = 11; var bestOfTwo = ScoreUtility.BestOfTwo(englishtest, experiment); var gpWindow = new NSAlert(); gpWindow.InformativeText = "the grade is" + gp + student.SendMessage(" This is a message for all the students" + " best of two: " + bestOfTwo); gpWindow.RunModal(); }
partial void btnCreate_Clicked(MonoMac.Foundation.NSObject sender) { if (txtData.Cell.Title.Length > 0 && txtIpBin.Cell.Title.Length > 0 && txtOutput.Cell.Title.Length > 0) { List <string> cdTracks = new List <string>(); foreach (CddaItem lvi in _tracks.Rows) { cdTracks.Add(lvi.FilePath); } string checkMsg = _builder.CheckOutputExists(cdTracks, txtOutput.Cell.Title); if (checkMsg != null) { NSAlert dialog = NSAlert.WithMessage("Warning", "No", "Yes", null, checkMsg); if (dialog.RunModal() == 1) { return; } } DisableButtons(); _builder.RawMode = (chkRawMode.State == NSCellStateValue.On); _builder.ReportProgress = UpdateProgress; string dataPath = txtData.Cell.Title; string ipBinPath = txtIpBin.Cell.Title; string outputPath = txtOutput.Cell.Title; _worker = new Thread(() => DoDiscBuild(dataPath, ipBinPath, cdTracks, outputPath)); _worker.Start(); } else { NSAlert.WithMessage("Error", "OK", null, null, "Not ready to build disc. Please provide more information above.").RunModal(); } }
private bool isValidCEP(String cep) { bool erro = true; if (cep.Length != 8) { var alert = new NSAlert() { AlertStyle = NSAlertStyle.Informational, InformativeText = "CEP deve conter 8 caracteres!", MessageText = "ERRO", }; alert.RunModal(); erro = false; } int cepValid = 0; if (!int.TryParse(cep, out cepValid)) { var alert = new NSAlert() { AlertStyle = NSAlertStyle.Informational, InformativeText = "CEP deve conter apenas números!", MessageText = "ERRO", }; alert.RunModal(); erro = false; } return(erro); }
public TodoItemManager() { // Has the application been configured with the developer's // Azure information? if (Constants.ApplicationURL == "") { // No, inform user var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, InformativeText = "Before this example can be successfully run, you need to provide your developer information used to access Azure.", MessageText = "Azure Not Configured", }; alert.RunModal(); } else { // Establish a link to Azure client = new MobileServiceClient( Constants.ApplicationURL, Constants.ApplicationKey); // Read any existing todo items from the Azure client this.todoTable = client.GetTable <TodoItem> (); } }
public static nint ShowAlert (String text, String caption) { var alert = new NSAlert (); alert.MessageText = caption; alert.InformativeText = text; return alert.RunModal (); }
/// <summary> /// Submits the button. /// </summary> /// <param name="sender">Sender.</param> partial void SubmitButton(NSObject sender) { try { // Get and set variables from form var busDirectionValue = BusDirectionComboBox.StringValue; var busStopValue = BusStopNameTextBox.StringValue; var busRouteValue = BusRouteTextBox.StringValue; // Run business logic var nextBus = new NextBusOperation(); var timeInMinutes = nextBus.GetTimeInMinutesForNextBus(busRouteValue, busStopValue, busDirectionValue); var stringToDisplay = timeInMinutes.ToString() + " minutes"; // Output Console.WriteLine(stringToDisplay); OutputTimeLabel.StringValue = stringToDisplay; } catch (Exception ex) { Console.WriteLine(ex.Message); OutputTimeLabel.StringValue = "Error"; var alert = new NSAlert { MessageText = "Error", InformativeText = ex.Message }; alert.RunModal(); } }
public override async void ViewDidLoad() { try { // Open SignalR connection to server await connection.StartAsync(); } catch (Exception e) { var alert = new NSAlert { MessageText = "Error", InformativeText = e.Message }; alert.RunModal(); throw; } await AuthorizeVideoInputUse(); while (VideoInputPermissionGranted == false) { await Task.Delay(50); } base.ViewDidLoad(); if (SetupCapture() == true) { if (captureSession.Running == false) { Console.WriteLine("AVCaptureSession failed to start running"); } } }
public override void DidFinishLaunching(NSNotification notification) { LocalExtensionManager = new ExtensionManager("com.userfilesystem.vfs.app", "ITHitFS6"); NSMenu menu = new NSMenu(); NSMenuItem installMenuItem = new NSMenuItem("Install FS Extension", (a, b) => { LocalExtensionManager.InstallExtension(); }); NSMenuItem uninstallMenuItem = new NSMenuItem("Uninstall FS Extension", (a, b) => { LocalExtensionManager.UninstallExtension(); }); NSMenuItem exitMenuItem = new NSMenuItem("Quit", (a, b) => { NSApplication.SharedApplication.Terminate(this); }); menu.AddItem(installMenuItem); menu.AddItem(uninstallMenuItem); menu.AddItem(exitMenuItem); StatusItem = NSStatusBar.SystemStatusBar.CreateStatusItem(30); StatusItem.Menu = menu; StatusItem.Image = NSImage.ImageNamed("TrayIcon.png"); StatusItem.HighlightMode = true; NSDictionary userData = AppGroupSettings.SaveSharedSettings("appsettings.json"); if (!Directory.Exists(userData[AppGroupSettings.LocalPathId] as NSString)) { NSAlert alert = NSAlert.WithMessage("Path is not found", null, null, null, ""); alert.RunModal(); NSApplication.SharedApplication.Terminate(this); } }
void HandleWindowWillClose(object sender, EventArgs e) { if (!Platform.MacPreferences.ShouldAskToStartAtLogin) { return; } var alert = new NSAlert { AlertStyle = NSAlertStyle.Informational, MessageText = "Would you like Awareness to start at login?", InformativeText = "Unless Awareness starts automatically, you will likely forget to use it. What good would that do you?" }; alert.AddButton("Start Awareness at Login"); alert.AddButton("No Thanks"); // TODO: Figure out why this freezes Awareness! // alert.BeginSheet (Window, this, new Selector ("alertDidEnd:returnCode:contextInfo:"), IntPtr.Zero); var pressed = (NSAlertButtonReturn)alert.RunModal(); if (pressed == NSAlertButtonReturn.First) { Log.Info("User consented to starting Awareness automatically at login."); Platform.Preferences.StartAtLogin = true; } Platform.MacPreferences.HasAskedToStartAtLogin = true; }
partial void OnDelete(Foundation.NSObject sender) { int row = (int)GuiTableEmails.SelectedRow; if (row < 0) { return; } PrivateEmailInfo email = __Model.PrivateEmails [row]; // Configure alert var alert = new NSAlert() { AlertStyle = NSAlertStyle.Informational, InformativeText = string.Format(LocalizedStrings.Instance.LocalizedString("Label_PrivateEmail_DeleteEmailQuestion_Informative_PARAMETRIZED"), email.Email), MessageText = string.Format(LocalizedStrings.Instance.LocalizedString("Label_PrivateEmail_DeleteEmailQuestion_Header_PARAMETRIZED"), email.Email), }; alert.AddButton(LocalizedStrings.Instance.LocalizedString("Button_Cancel")); alert.AddButton(LocalizedStrings.Instance.LocalizedString("Button_PrivateEmail_Delete")); nint result = alert.RunModal(); if (result == (int)NSAlertButtonReturn.Second) { // Remove the given row from the dataset __Model.DeleteEmail(email); } ; }
public override void AwakeFromNib () { base.AwakeFromNib (); // Show when the document is edited documentEditor.TextDidChange += (sender, e) => { // Mark the document as dirty DocumentEdited = true; }; // Overriding this delegate is required to monitor the TextDidChange event documentEditor.ShouldChangeTextInRanges += (NSTextView view, NSValue[] values, string[] replacements) => { return true; }; WillClose += (sender, e) => { // is the window dirty? if (DocumentEdited) { var alert = new NSAlert () { AlertStyle = NSAlertStyle.Critical, InformativeText = "We need to give the user the ability to save the document here...", MessageText = "Save Document", }; alert.RunModal (); } }; }
private bool CheckSave() { ParseProject(); if (_last_save == Sjson.Encode(JsonSerializer.Save(_project))) { return(true); } NSAlert alert = new NSAlert(); alert.AddButton(@"Save"); alert.AddButton(@"Don't Save"); alert.AddButton(@"Cancel"); alert.MessageText = @"Do you want to save changes to this document before closing?"; alert.InformativeText = @"If you don't save, your changes will be lost."; alert.AlertStyle = NSAlertStyle.Informational; int result = alert.RunModal(); if (result == (int)NSAlertButtonReturn.First) { saveProject(null); return(_file != null); } else if (result == (int)NSAlertButtonReturn.Second) { return(true); } else { return(false); } }
partial void Uninstall(NSObject sender) { if (!WaitUntilAnotherVersionIsClosed()) { return; } if (!DoUninstall()) { NSAlert alert = NSAlert.WithMessage( "There was an error while uninstalling IVPN Client.", "OK", null, null, "IVPN client could not be uninstalled"); var runModalResult = alert.RunModal(); if (runModalResult == 1) { return; } return; } IsUninstalled = true; }
public override void ViewDidLoad() { base.ViewDidLoad(); // Do any additional setup after loading the view. try { Process ffmpeg = new Process(); ffmpeg.StartInfo.UseShellExecute = true; ffmpeg.StartInfo.FileName = "ffmpeg"; ffmpeg.StartInfo.CreateNoWindow = true; ffmpeg.Start(); } catch { var text = "You are missing a dependency which this application " + "relies on. Transcoding is done with ffmpeg. Please install " + "ffmpeg and try again."; var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, InformativeText = text, MessageText = "Missing Dependency", }; alert.RunModal(); NSApplication.SharedApplication.Terminate(this); } }
private bool ValidateExportFolder(string path) { // We must select the Tiled2Unity.export.txt file in the Unity project string export = "Tiled2Unity.export.txt"; if (String.Compare(export, Path.GetFileName(path), true) != 0) { string title = "Choose File: " + export; StringBuilder message = new StringBuilder(); message.AppendLine("Choose the file named Tiled2Unity.export.txt in your Unity project"); message.AppendLine("This is needed for Tiled2Unity to know where to export files to."); message.AppendLine("\nexample: /Users/JoeBlow/UnityProject/Assets/Tiled2Unity/Tiled2Unity.export.txt"); var alert = new NSAlert() { AlertStyle = NSAlertStyle.Informational, InformativeText = message.ToString(), MessageText = title }; alert.RunModal(); return(false); } return(true); }
/// <summary> /// Shows the input dialog. /// </summary> /// <returns>The input</returns> /// <param name="name">Name.</param> /// <param name="providerName">Provider name.</param> public static string ShowInputDialog(string name, string providerName, bool multiline = false) { NSAlert alert = new NSAlert(); alert.MessageText = name.UppercaseFirst() + " is required by " + providerName; alert.AddButton("Ok"); alert.AddButton("Cancel"); CoreGraphics.CGRect textFieldRect = new CoreGraphics.CGRect(0, 0, 300, 24); if (multiline) { textFieldRect = new CoreGraphics.CGRect(0, 0, 300, 24 * 3); } SSTextField input = new SSTextField(textFieldRect); input.UsesSingleLineMode = !multiline; var clip = GetClipboard(); input.StringValue = (clip != null) ? clip : ""; alert.AccessoryView = input; nint button = alert.RunModal(); if (button == (int)NSAlertButtonReturn.First) { return(input.StringValue); } return(""); }
public override void KeyDown(NSEvent theEvent) { base.KeyDown(theEvent); if (theEvent.KeyCode == (int)NSKey.Delete) { if (GetView(0, SelectedRow, false) is IEditableView view) { if (view.IsBeingEdited) { return; } if (!view.CanBeDeleted) { return; } var alert = new NSAlert { MessageText = "Delete?", InformativeText = "", AlertStyle = NSAlertStyle.Warning, }; alert.AddButton("Yes"); alert.AddButton("No"); if (alert.RunModal() == 1000) { OnRowDelete(GetView(0, SelectedRow, false), new DeletePressedEventArgs((int)SelectedRow)); } } } }
AlertFlags IAlertPopup.ShowPopup(string caption, string text, AlertFlags flags) { NSAlertStyle style = NSAlertStyle.Informational; if ((flags & AlertFlags.WarningIcon) != 0) { style = NSAlertStyle.Warning; } var alert = new NSAlert() { AlertStyle = style, MessageText = caption, InformativeText = text, }; var buttons = new List <AlertFlags>(); Action <AlertFlags, string> addBtn = (code, txt) => { if ((flags & code) == 0) { return; } alert.AddButton(txt); buttons.Add(code); }; addBtn(AlertFlags.Ok, "OK"); addBtn(AlertFlags.Yes, "Yes"); addBtn(AlertFlags.No, "No"); addBtn(AlertFlags.Cancel, "Cancel"); nint idx = alert.RunModal() - 1000; return((idx >= 0 && idx < buttons.Count) ? buttons[(int)idx] : AlertFlags.None); }
/// <summary> /// Load the beat from the specified file name. /// </summary> /// <returns>The load.</returns> /// <param name="fileName">File name.</param> static public void Load(string fileName) { var ds = new DataContractSerializer(typeof(Pronome.Metronome)); using (Stream s = File.OpenRead(fileName)) { using (var r = XmlDictionaryReader.CreateBinaryReader(s, XmlDictionaryReaderQuotas.Max)) { try { var m = ds.ReadObject(r) as Pronome.Metronome; ImportMetronome(m); CurrentlyOpenFile = fileName; } catch (SerializationException) { string name = Path.GetFileName(fileName); var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, InformativeText = $"{name} could not be used because it isn't a valid beat file.", MessageText = "Invalid Beat File" }; alert.RunModal(); } } } }
partial void LaunchAction(NSObject sender) { if (Directory.Exists(DirectoryField.StringValue)) { if (!Directory.Exists(Path.Combine(DirectoryField.StringValue, "DATA")) || !Directory.Exists(Path.Combine(DirectoryField.StringValue, "EXE"))) { var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, InformativeText = "Not a valid freelancer directory.", MessageText = "Error", }; alert.RunModal(); return; } MainClass.LaunchPath = DirectoryField.StringValue; MainClass.MuteMusic = MuteMusic.State == NSCellStateValue.On; MainClass.SkipIntroMovies = SkipIntroMovies.State == NSCellStateValue.On; NSApplication.SharedApplication.Stop(this); } else { var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, InformativeText = "Path does not exist.", MessageText = "Error", }; alert.RunModal(); } }
partial void ClickedButton(Foundation.NSObject sender) { // Update counter and label ClickedLabel.StringValue = string.Format("The button has been clicked {0} time{1}.", ++numberOfTimesClicked, (numberOfTimesClicked < 2) ? "" : "s"); var testSchool = new School(); testSchool.Name = txtName.StringValue; testSchool.Address = txtAddress.StringValue; testSchool.City = txtCity.StringValue; testSchool.State = txtState.StringValue; testSchool.Zip = txtZip.StringValue; testSchool.PhoneNumber = txtPhone.StringValue; try { testSchool.TwitterAddress = txtTwitter.StringValue; //@City High } catch (Exception ex) { var alert = new NSAlert(); alert.MessageText = "error"; alert.InformativeText = ex.Message; alert.RunModal(); } var resultWindow = new NSAlert(); resultWindow.MessageText = "result"; resultWindow.InformativeText = testSchool.ToString(); resultWindow.RunModal(); }
private void RunSaveDialog() { // Create the Save alert. string alertTitle = "Save Festival Data"; string okButtonTitle = "OK"; string informativeText = $"Please hit the {okButtonTitle} button to save the {Festival}{FestivalYear} data"; var alert = new NSAlert() { AlertStyle = NSAlertStyle.Informational, MessageText = alertTitle, InformativeText = informativeText, }; alert.AddButton(okButtonTitle); alert.AddButton("Cancel"); // Run the alert. var alertResult = alert.RunModal(); // Take action based on the button pressed. if (alertResult == 1000) { SaveFestivalData(); } }
public /* Interface KGuiControl */ void GuiChartData() { if (NSThread.IsMain) { // because of sandboxing, we must use the official Save Dialog to automatically create an exception and allow writing the file? var dlg = new NSSavePanel(); dlg.Title = "Save CSV File"; dlg.AllowedFileTypes = new string[] { "csv" }; dlg.Directory = MacControls.modelsDirectory; if (dlg.RunModal() == 1) { var path = ""; try { path = dlg.Url.Path; File.WriteAllText(path, KChartHandler.ToCSV(), System.Text.Encoding.Unicode); } catch { var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, MessageText = "Could not write this file:", InformativeText = path }; alert.RunModal(); } } } else { _ = BeginInvokeOnMainThreadAsync(() => { GuiChartData(); return(ack); }).Result; } }
public static void Present(this UserPresentableException e, object uiContext = null) { Log.Error(TAG, $"{e.Message} ({e.Details})", e.InnerException ?? e); MainThread.Ensure(); uiContext = uiContext ?? e.UIContext; var window = (uiContext as NSViewController)?.View?.Window ?? (uiContext as NSView)?.Window ?? (uiContext as NSWindowController)?.Window ?? uiContext as NSWindow; var alert = new NSAlert { AlertStyle = NSAlertStyle.Critical, MessageText = e.Message, InformativeText = e.Details }; if (window == null) { alert.RunModal(); } else { alert.BeginSheet(window, resp => { }); } }
public static void OperationFailureHandler(string message, ProgressContext context) { new NSObject().InvokeOnMainThread(() => { NSAlert alert = NSAlert.WithMessage(message, "OK", null, null, "Check your password and try again"); alert.RunModal(); }); }
public /* Interface KGuiControl */ void GuiChartSnapToSvg() { if (NSThread.IsMain) { string svg = Export.SnapToSVG(GuiChartSize()); var dlg = new NSSavePanel(); dlg.Title = "Save SVG File"; dlg.AllowedFileTypes = new string[] { "svg" }; dlg.Directory = MacControls.modelsDirectory; if (dlg.RunModal() == 1) { var path = ""; try { path = dlg.Url.Path; File.WriteAllText(path, svg, System.Text.Encoding.Unicode); } catch { var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, MessageText = "Could not write this file:", InformativeText = path }; alert.RunModal(); } } } else { _ = BeginInvokeOnMainThreadAsync(() => { GuiChartSnapToSvg(); return(ack); }).Result; } }
public void Load() { var dlg = NSOpenPanel.OpenPanel; dlg.Title = "Open Text File"; dlg.CanChooseFiles = true; dlg.CanChooseDirectories = false; dlg.Directory = modelsDirectory; dlg.AllowedFileTypes = new string[] { "txt" }; if (dlg.RunModal() == 1) { var path = ""; try { path = dlg.Urls[0].Path; KGui.gui.GuiInputSetText(File.ReadAllText(path, System.Text.Encoding.Unicode)); } catch { var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, MessageText = "Could not load this file:", InformativeText = path }; alert.RunModal(); } } }
static void ShowVoiceOverNotice() { var alert = new NSAlert(); alert.MessageText = GettextCatalog.GetString("Assistive Technology Detected"); alert.InformativeText = GettextCatalog.GetString("{0} has detected an assistive technology (such as VoiceOver) is running. Do you want to restart {0} and enable the accessibility features?", BrandingService.ApplicationName); alert.AddButton(GettextCatalog.GetString("Restart and enable")); alert.AddButton(GettextCatalog.GetString("No")); var result = alert.RunModal(); switch (result) { case 1000: NSUserDefaults defaults = NSUserDefaults.StandardUserDefaults; defaults.SetBool(true, EnabledKey); defaults.Synchronize(); IdeApp.Restart(); break; default: break; } }
void OpenDialog(NSObject sender) { var dlg = NSOpenPanel.OpenPanel; dlg.CanChooseFiles = false; dlg.CanChooseDirectories = true; if (dlg.RunModal() == 1) { var url = dlg.Urls.FirstOrDefault(); if (url != null) { var path = url.Path; if (Directory.Exists(Path.Combine(path, "en")) && File.Exists(Path.Combine(path, "en", "index.xml"))) { OpenDir(Path.Combine(path, "en")); SaveStatus(); } else { var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, InformativeText = "The selected directory is not the toplevel directory for ECMA XML documentation. Those should contain a subdirectory en and a file en/index.xml", MessageText = "Not an ECMA XML Documentation Directory", }; alert.RunModal(); } } } }
private void AdjustLibraryKeywordGroup(NSTextField textField, int row) { if (!_dataSource.Keywords[row].IsNew) { if (textField.StringValue.ToLower().Trim() != _dataSource.Keywords[row].GroupName.ToLower().Trim()) { var alertDialog = new NSAlert { AlertStyle = NSAlertStyle.Warning, MessageText = $"Are you sure you wish to overwrite keyword group \"{_dataSource.Keywords[row].GroupName}\" with \"{textField.StringValue}\"?", InformativeText = "This will rename keyword group for all sources in library as well.", }; alertDialog.AddButton("Yes"); alertDialog.AddButton("No"); var choice = alertDialog.RunModal(); if (choice == 1000) { _dataSource.Keywords[row].GroupName = textField.StringValue; } else if (choice == 1001) { textField.StringValue = _dataSource.Keywords[row].GroupName; } } } else { _dataSource.Keywords[row].GroupName = textField.StringValue; } }
// The user just clicked the Show Message NSButton, so we show him/her // a greeting. This code shows you how to execute C# code when a click is done in // and HTML button. public override void HandleEvent (DomEvent evt) { var alert = new NSAlert () { MessageText = "Hello there", InformativeText = "Saying hello from C# code. Event type: " + evt.Type }; alert.RunModal(); }
public static void Show (string messageText) { var alert = new NSAlert () { AlertStyle = NSAlertStyle.Informational, InformativeText = string.Empty, MessageText = messageText, }; alert.RunModal (); }
public static void Show(IntPtr owner, string text, string caption) { #if WINDOWS PInvokeWindows.MessageBox(owner, text, caption, PInvokeWindows.MessageBoxOptions.OkOnly | PInvokeWindows.MessageBoxOptions.IconExclamation); #elif OSX NSAlert alert = new NSAlert(); alert.MessageText = text; alert.RunModal(); #endif }
void OpenDialog (NSObject sender) { var dlg = NSOpenPanel.OpenPanel; dlg.CanChooseFiles = false; dlg.CanChooseDirectories = true; if (dlg.RunModal () == 1) { var alert = new NSAlert () { AlertStyle = NSAlertStyle.Informational, InformativeText = "At this point we should do something with the folder that the user just selected in the Open File Dialog box...", MessageText = "Folder Selected" }; alert.RunModal (); } }
public static bool ShowConfirm (String text, String caption) { var oAlert = new NSAlert(); // Set the buttons oAlert.AddButton("Yes"); oAlert.AddButton("No"); // Show the message box and capture oAlert.MessageText = caption; oAlert.InformativeText = text; oAlert.AlertStyle = NSAlertStyle.Warning; oAlert.Icon = NSImage.ImageNamed (NSImageName.Caution); var responseAlert = oAlert.RunModal(); return (responseAlert == 1000); }
public override void ViewWillAppear () { base.ViewWillAppear (); // Set Window Title this.View.Window.Title = "untitled"; View.Window.WillClose += (sender, e) => { // is the window dirty? if (DocumentEdited) { var alert = new NSAlert () { AlertStyle = NSAlertStyle.Critical, InformativeText = "We need to give the user the ability to save the document here...", MessageText = "Save Document", }; alert.RunModal (); } }; }
public static bool ConfirmDeleteOperation (string confirmMessage) { try { var oAlert = new NSAlert(); // Set the buttons oAlert.AddButton("Yes"); oAlert.AddButton("No"); // Show the message box and capture oAlert.MessageText = confirmMessage; oAlert.InformativeText = "Confirmation"; oAlert.AlertStyle = NSAlertStyle.Warning; oAlert.Icon = NSImage.ImageNamed (NSImageName.Caution); var responseAlert = oAlert.RunModal(); return (responseAlert == 1000); //returns 1001 for No and 1000 for Yes in this case } catch (Exception e) { throw e; } }
public TodoItemManager() { // Has the application been configured with the developer's // Azure information? if (Constants.ApplicationURL == "") { // No, inform user var alert = new NSAlert () { AlertStyle = NSAlertStyle.Critical, InformativeText = "Before this example can be successfully run, you need to provide your developer information used to access Azure.", MessageText = "Azure Not Configured", }; alert.RunModal (); } else { // Establish a link to Azure client = new MobileServiceClient ( Constants.ApplicationURL, Constants.ApplicationKey); // Read any existing todo items from the Azure client this.todoTable = client.GetTable<TodoItem> (); } }
public bool Run (AlertDialogData data) { using (var alert = new NSAlert ()) { alert.Window.Title = data.Title ?? BrandingService.ApplicationName; IdeTheme.ApplyTheme (alert.Window); bool stockIcon; if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Error || data.Message.Icon == Gtk.Stock.DialogError) { alert.AlertStyle = NSAlertStyle.Critical; stockIcon = true; } else if (data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Warning || data.Message.Icon == Gtk.Stock.DialogWarning) { alert.AlertStyle = NSAlertStyle.Critical; stockIcon = true; } else { alert.AlertStyle = NSAlertStyle.Informational; stockIcon = data.Message.Icon == MonoDevelop.Ide.Gui.Stock.Information; } if (!stockIcon && !string.IsNullOrEmpty (data.Message.Icon)) { var img = ImageService.GetIcon (data.Message.Icon, Gtk.IconSize.Dialog); // HACK: VK The icon is not rendered in dark style correctly // Use light variant and reder it here // as long as NSAppearance.NameVibrantDark is broken if (IdeTheme.UserInterfaceTheme == Theme.Dark) alert.Icon = img.WithStyles ("-dark").ToBitmap (GtkWorkarounds.GetScaleFactor ()).ToNSImage (); else alert.Icon = img.ToNSImage (); } else { //for some reason the NSAlert doesn't pick up the app icon by default alert.Icon = NSApplication.SharedApplication.ApplicationIconImage; } alert.MessageText = data.Message.Text; alert.InformativeText = data.Message.SecondaryText ?? ""; var buttons = data.Buttons.Reverse ().ToList (); for (int i = 0; i < buttons.Count - 1; i++) { if (i == data.Message.DefaultButton) { var next = buttons[i]; for (int j = buttons.Count - 1; j >= i; j--) { var tmp = buttons[j]; buttons[j] = next; next = tmp; } break; } } var wrappers = new List<AlertButtonWrapper> (buttons.Count); foreach (var button in buttons) { var label = button.Label; if (button.IsStockButton) label = Gtk.Stock.Lookup (label).Label; label = label.Replace ("_", ""); //this message seems to be a standard Mac message since alert handles it specially if (button == AlertButton.CloseWithoutSave) label = GettextCatalog.GetString ("Don't Save"); var nsbutton = alert.AddButton (label); var wrapperButton = new AlertButtonWrapper (nsbutton, data.Message, button, alert); wrappers.Add (wrapperButton); nsbutton.Target = wrapperButton; nsbutton.Action = new ObjCRuntime.Selector ("buttonActivatedAction"); } NSButton[] optionButtons = null; if (data.Options.Count > 0) { var box = new MDBox (LayoutDirection.Vertical, 2, 2); optionButtons = new NSButton[data.Options.Count]; for (int i = data.Options.Count - 1; i >= 0; i--) { var option = data.Options[i]; var button = new NSButton { Title = option.Text, Tag = i, State = option.Value? NSCellStateValue.On : NSCellStateValue.Off, }; button.SetButtonType (NSButtonType.Switch); optionButtons[i] = button; box.Add (new MDAlignment (button, true) { XAlign = LayoutAlign.Begin }); } box.Layout (); alert.AccessoryView = box.View; } NSButton applyToAllCheck = null; if (data.Message.AllowApplyToAll) { alert.ShowsSuppressionButton = true; applyToAllCheck = alert.SuppressionButton; applyToAllCheck.Title = GettextCatalog.GetString ("Apply to all"); } // Hack up a slightly wider than normal alert dialog. I don't know how to do this in a nicer way // as the min size constraints are apparently ignored. var frame = alert.Window.Frame; alert.Window.SetFrame (new CGRect (frame.X, frame.Y, NMath.Max (frame.Width, 600), frame.Height), true); alert.Layout (); bool completed = false; if (data.Message.CancellationToken.CanBeCanceled) { data.Message.CancellationToken.Register (delegate { alert.InvokeOnMainThread (() => { if (!completed) { NSApplication.SharedApplication.AbortModal (); } }); }); } if (!data.Message.CancellationToken.IsCancellationRequested) { var result = (int)alert.RunModal () - (long)(int)NSAlertButtonReturn.First; completed = true; if (result >= 0 && result < buttons.Count) { data.ResultButton = buttons [(int)result]; } else { data.ResultButton = null; } } if (data.ResultButton == null || data.Message.CancellationToken.IsCancellationRequested) { data.SetResultToCancelled (); } if (optionButtons != null) { foreach (var button in optionButtons) { var option = data.Options[(int)button.Tag]; data.Message.SetOptionValue (option.Id, button.State != 0); } } if (applyToAllCheck != null && applyToAllCheck.State != 0) data.ApplyToAll = true; GtkQuartz.FocusWindow (data.TransientFor ?? MessageService.RootWindow); } return true; }
void ShowLayout (NSObject sender) { var dlg = new NSPageLayout(); // Display the print dialog as dialog box if (ShowPrintAsSheet) { dlg.BeginSheet (new NSPrintInfo (), this); } else { if (dlg.RunModal () == 1) { var alert = new NSAlert () { AlertStyle = NSAlertStyle.Critical, InformativeText = "We need to print the document here...", MessageText = "Print Document", }; alert.RunModal (); } } }
void ShowAlert (NSObject sender) { if (ShowAlertAsSheet) { var input = new NSTextField (new CGRect (0, 0, 300, 20)); var alert = new NSAlert () { AlertStyle = NSAlertStyle.Informational, InformativeText = "This is the body of the alert where you describe the situation and any actions to correct it.", MessageText = "Alert Title", }; alert.AddButton ("Ok"); alert.AddButton ("Cancel"); alert.AddButton ("Maybe"); alert.ShowsSuppressionButton = true; alert.AccessoryView = input; alert.Layout (); alert.BeginSheetForResponse (this, (result) => { Console.WriteLine ("Alert Result: {0}, Suppress: {1}", result, alert.SuppressionButton.State == NSCellStateValue.On); }); } else { var input = new NSTextField (new CGRect (0, 0, 300, 20)); var alert = new NSAlert () { AlertStyle = NSAlertStyle.Informational, InformativeText = "This is the body of the alert where you describe the situation and any actions to correct it.", MessageText = "Alert Title", }; alert.AddButton ("Ok"); alert.AddButton ("Cancel"); alert.AddButton ("Maybe"); alert.ShowsSuppressionButton = true; alert.AccessoryView = input; alert.Layout (); var result = alert.RunModal (); Console.WriteLine ("Alert Result: {0}, Suppress: {1}", result, alert.SuppressionButton.State == NSCellStateValue.On); } }
void ShowDocument (NSObject sender) { var dlg = new NSPrintPanel(); // Display the print dialog as dialog box if (ShowPrintAsSheet) { dlg.BeginSheet(new NSPrintInfo(),this,this,null,new IntPtr()); } else { if (dlg.RunModalWithPrintInfo(new NSPrintInfo()) == 1) { var alert = new NSAlert () { AlertStyle = NSAlertStyle.Warning, InformativeText = "We need to print the document here...", MessageText = "Print Document", }; alert.RunModal (); } } }
public bool Run (ExceptionDialogData data) { using (var alert = new NSAlert { AlertStyle = NSAlertStyle.Critical }) { alert.Icon = NSApplication.SharedApplication.ApplicationIconImage; alert.MessageText = data.Title ?? GettextCatalog.GetString ("Error"); if (!string.IsNullOrEmpty (data.Message)) { alert.InformativeText = data.Message; } List<AlertButton> buttons = null; if (data.Buttons != null && data.Buttons.Length > 0) buttons = data.Buttons.Reverse ().ToList (); if (buttons != null) { foreach (var button in buttons) { var label = button.Label; if (button.IsStockButton) label = Gtk.Stock.Lookup (label).Label; label = label.Replace ("_", ""); //this message seems to be a standard Mac message since alert handles it specially if (button == AlertButton.CloseWithoutSave) label = GettextCatalog.GetString ("Don't Save"); alert.AddButton (label); } } if (data.Exception != null) { var scrollSize = new CGSize (400, 130); const float spacing = 4; string title = GettextCatalog.GetString ("View details"); string altTitle = GettextCatalog.GetString ("Hide details"); var buttonFrame = new CGRect (0, 0, 0, 0); var button = new NSButton (buttonFrame) { BezelStyle = NSBezelStyle.Disclosure, Title = "", AlternateTitle = "", }; button.SetButtonType (NSButtonType.OnOff); button.SizeToFit (); var label = new MDClickableLabel (title) { Alignment = NSTextAlignment.Left, }; label.SizeToFit (); button.SetFrameSize (new CGSize (button.Frame.Width, NMath.Max (button.Frame.Height, label.Frame.Height))); label.SetFrameOrigin (new CGPoint (button.Frame.Width + 5, button.Frame.Y)); var text = new MyTextView (new CGRect (0, 0, float.MaxValue, float.MaxValue)) { HorizontallyResizable = true, }; text.TextContainer.ContainerSize = new CGSize (float.MaxValue, float.MaxValue); text.TextContainer.WidthTracksTextView = true; text.InsertText (new NSString (data.Exception.ToString ())); text.Editable = false; var scrollView = new NSScrollView (new CGRect (CGPoint.Empty, CGSize.Empty)) { HasHorizontalScroller = true, HasVerticalScroller = true, }; var accessory = new NSView (new CGRect (0, 0, scrollSize.Width, button.Frame.Height)); accessory.AddSubview (scrollView); accessory.AddSubview (button); accessory.AddSubview (label); alert.AccessoryView = accessory; button.Activated += delegate { nfloat change; if (button.State == NSCellStateValue.On) { change = scrollSize.Height + spacing; label.StringValue = altTitle; scrollView.Hidden = false; scrollView.Frame = new CGRect (CGPoint.Empty, scrollSize); scrollView.DocumentView = text; } else { change = -(scrollSize.Height + spacing); label.StringValue = title; scrollView.Hidden = true; scrollView.Frame = new CGRect (CGPoint.Empty, CGSize.Empty); } var f = accessory.Frame; f.Height += change; accessory.Frame = f; var lf = label.Frame; lf.Y += change; label.Frame = lf; var bf = button.Frame; bf.Y += change; button.Frame = bf; label.SizeToFit (); var panel = alert.Window; var pf = panel.Frame; pf.Height += change; pf.Y -= change; panel.SetFrame (pf, true, true); //unless we assign the icon again, it starts nesting old icon into the warning icon alert.Icon = NSApplication.SharedApplication.ApplicationIconImage; alert.Layout (); }; label.OnMouseUp += (sender, e) => button.PerformClick (e.Event); } var result = (int)(nint)alert.RunModal () - (int)(long)NSAlertButtonReturn.First; data.ResultButton = buttons != null ? buttons [result] : null; GtkQuartz.FocusWindow (data.TransientFor ?? MessageService.RootWindow); } return true; }
public bool ContinueIfChanged() { if (Window.Subtitle.Paragraphs.Count == 0 || Window.Subtitle.GetFastHashCode() == _subtitleOriginalHash) { return true; } NSAlert alert = new NSAlert(); if (_subtitleFileName == null) { alert.MessageText = _language.SaveChangesToUntitled; } else { alert.MessageText = string.Format(_language.SaveChangesToX, _subtitleFileName); } alert.AddButton("Yes".Replace("&", string.Empty)); alert.AddButton("No".Replace("&", string.Empty)); alert.AddButton(_languageGeneral.Cancel.Replace("&", string.Empty)); var result = alert.RunModal(); if (result == (long)(NSAlertButtonReturn.First)) { return SaveSubtitle(); } else if (result == (long)(NSAlertButtonReturn.Second)) { Window.Subtitle.Paragraphs.Clear(); return true; } return false; }
public void DeleteLines() { var selectedRows = Window.SubtitleTable.SelectedRows; if (selectedRows.Count == 0) return; if (Configuration.Settings.General.PromptDeleteLines) { NSAlert alert = new NSAlert(); var count = selectedRows.Count; alert.MessageText = count == 1 ? _language.DeleteOneLinePrompt : string.Format(_language.DeleteXLinesPrompt, count); alert.AddButton(_languageGeneral.Ok.Replace("&", string.Empty)); alert.AddButton(_languageGeneral.Cancel.Replace("&", string.Empty)); var result = alert.RunModal(); if (result != (long)(NSAlertButtonReturn.First)) { return; } } foreach (var row in selectedRows.Reverse()) { Window.Subtitle.Paragraphs.RemoveAt((int)row); } Window.Subtitle.Renumber(); Window.SubtitleTable.ReloadData(); ShowSubtitleRow((nint)selectedRows.First()); }
void Run (NSAlert alert) { switch (AlertOptions.SelectedTag) { case 0: alert.BeginSheetForResponse (Window, response => ShowResponse (alert, response)); break; case 1: ShowResponse (alert, (int)alert.RunSheetModal (Window)); break; case 2: ShowResponse (alert, (int)alert.RunModal ()); break; default: ResultLabel.StringValue = "Unknown Alert Option"; break; } }
void ShowSaveAs (NSObject sender) { var dlg = new NSSavePanel (); dlg.Title = "Save Text File"; if (ShowSaveAsSheet) { dlg.BeginSheet(mainWindowController.Window,(result) => { var alert = new NSAlert () { AlertStyle = NSAlertStyle.Critical, InformativeText = "We need to save the document here...", MessageText = "Save Document", }; alert.RunModal (); }); } else { if (dlg.RunModal () == 1) { var alert = new NSAlert () { AlertStyle = NSAlertStyle.Critical, InformativeText = "We need to save the document here...", MessageText = "Save Document", }; alert.RunModal (); } } }