private void CopySelection() { int first = Math.Min(selectionStart.Index, cursorPosition.Index); int length = Math.Max(selectionStart.Index, cursorPosition.Index) - first; Clipboard.SetText(text.Substring(first, length)); }
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (cmdGroup == VsMenus.guidStandardCommandSet2K) { switch ((VsCommands2K)cmd) { case CommonConstants.OpenFolderInExplorerCmdId: Process.Start(new ProcessStartInfo { FileName = _factory.Configuration.PrefixPath, Verb = "open", UseShellExecute = true }); return VSConstants.S_OK; } } if (cmdGroup == ProjectMgr.SharedCommandGuid) { switch ((SharedCommands)cmd) { case SharedCommands.OpenCommandPromptHere: var pyProj = ProjectMgr as PythonProjectNode; if (pyProj != null && _factory != null && _factory.Configuration != null) { return pyProj.OpenCommandPrompt( _factory.Configuration.PrefixPath, _factory, _factory.Configuration.FullDescription ); } break; case SharedCommands.CopyFullPath: Clipboard.SetText(_factory.Configuration.InterpreterPath); return VSConstants.S_OK; } } return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut); }
protected override void EndProcessing() { ExecuteWrite(delegate { WinFormsClipboard.SetText(_output.ToString()); }); }
public void click() { try { if (this.Application.ActiveExplorer().Selection.Count > 0) { Object selObject = this.Application.ActiveExplorer().Selection[1]; if (selObject is Outlook.MailItem) { Outlook.MailItem mailItem = (selObject as Outlook.MailItem); string copyText = string.Format("To: {0}\nFrom: {1}\nDate: {2}\nSubject: {3}\nBody: {4}", mailItem.To, mailItem.Sender.Address, mailItem.ReceivedTime, mailItem.Subject, ThisAddIn.filterBody(mailItem.Body)); Clipboard.SetDataObject(copyText); } } } catch (Exception ex) { // Log errors ? } }
/// <summary> /// Metodo que muestra muestra el logo del reporte /// </summary> private void CrearLogo() { if (MostrarLogo) { var ruta = new Uri(string.Format("/SIAP;component/Imagenes/ReporteLogo.png"), UriKind.Relative); StreamResourceInfo streamLogo = System.Windows.Application.GetResourceStream(ruta); Image logoSK = null; if (streamLogo != null) { Stream imagenStream = streamLogo.Stream; logoSK = Image.FromStream(imagenStream); } if (logoSK != null) { Clipboard.Clear(); Clipboard.SetImage(logoSK); if (Clipboard.ContainsImage()) { hoja.Paste(); var p = (Pictures)hoja.Pictures(Missing.Value); var pic = (Picture)p.Item(p.Count); pic.Height = 30; pic.Width = 80; pic.Top = 15; pic.Left = rango.Left; } streamLogo = null; logoSK.Dispose(); logoSK = null; } } }
public async Task ConvertToPrismProperty() { await Task.Factory.StartNew(() => { //cut the current line const string function = "CopyLine(){\r\nSend, ^x\r\nclipboard := Clipboard\r\nreturn clipboard\r\n}"; ahk.ExecRaw(function); string eval = ahk.Eval("CopyLine()"); string line = eval.Trim().Trim('\n'); //trim spaces and line breaks if (string.IsNullOrWhiteSpace(line)) { return; } string[] split = line.Split(' '); string propertyType = split[1]; string propertyName = split[2]; string lowercase = $"{propertyName[0].ToString().ToLower()}{propertyName.Substring(1)}"; var pattern = @" private {2} {0}; public {2} {1} {{ get => {0}; set => SetProperty(ref {0},value); }} "; pattern = string.Format(pattern, lowercase, propertyName, propertyType); Application.Current.Dispatcher?.Invoke(() => Clipboard.SetText(pattern)); var paste = "Send, ^v"; ahk.ExecRaw(paste); }); }
private void DoShowUniqueID() { var LApp = (IAppTaxApplicationService)_appInstance; var LKey = LApp.GetMachineIdentifier(); MessageBox.Show(string.Format("{0}\n The Unique ID is copied to clipboard", string.IsNullOrEmpty(LKey) ? "No unlock key assigned" : LKey)); Clipboard.SetText(LKey); }
static public void SetText(string text) { try { NClipboard.SetText(text); } catch { } }
private void DoShowUnlockKey() { var LApp = (IAppTaxApplicationService)_appInstance; var LConfig = LApp.Configuration; var LKey = LConfig.AsString("Application", "UnlockKey", ""); MessageBox.Show(string.Format("{0}\n The code is copied to clipboard", string.IsNullOrEmpty(LKey) ? "No unlock key assigned" : LKey)); Clipboard.SetText(LKey); }
private static bool HasClipboardPowerpointSlideContent() { var data = Clipboard.GetDataObject(); if (data == null) { return(false); } var formats = data.GetFormats(); return(formats.Any(f => f.StartsWith("PowerPoint"))); }
public string Classify(string work, out bool isEol) { // Log.Debug(new StackFrame(0, true)); string tempstring = Clipboard.GetText(); //Clipboard.Clear(); isEol = Regex.IsMatch(tempstring, @"reaching the end"); if (Replace(ref work, tempstring, out string replace)) { return(replace); }
static public void ToPlainText() { try { if (NClipboard.ContainsText()) { string text = NClipboard.GetText(); NClipboard.SetText(text); //all formatting (e.g. RTF) will be removed } } catch { } }
public void BackupFunc() { if (InfoTab.AppState != AppStates.Awaiting) { InfoTab = new InfoTabViewItem(AppStates.IsBusy); OnPropertyChanged(nameof(InfoTab)); try { var fileName = $"{ConnectionStringModel.DbNameText} Backup {DateTime.Now.ToShortDateString()}.bak"; using (SqlConnection connection = new SqlConnection(ConnectionStringModel.ConnectionString)) { var commandText = $@"BACKUP DATABASE {ConnectionStringModel.DbNameText} TO DISK = N'{ConnectionStringModel.PathText}\{fileName}' WITH NOFORMAT, INIT, NAME = N'{ConnectionStringModel.DbNameText}-Полная База данных Резервное копирование', SKIP, NOREWIND, NOUNLOAD, STATS = 10"; var command = new SqlCommand(commandText, connection); command.CommandText = commandText; command.CommandTimeout = 3000; connection.Open(); command.ExecuteNonQuery(); } if (Settings.Default.Paths != null) { if (!Settings.Default.Paths.Contains(ConnectionStringModel.PathText) && !string.IsNullOrEmpty(ConnectionStringModel.PathText)) { Settings.Default.Paths.Add(ConnectionStringModel.PathText); Settings.Default.Save(); } } else { Settings.Default.Paths = new System.Collections.Specialized.StringCollection(); Settings.Default.Paths.Add(ConnectionStringModel.PathText); Settings.Default.Save(); } InfoTab = new InfoTabViewItem(AppStates.SuccessfullyBackuped); OnPropertyChanged(nameof(InfoTab)); } catch (Exception ex) { Clipboard.SetText(ex.Message); InfoTab = new InfoTabViewItem(AppStates.BackupError); OnPropertyChanged(nameof(InfoTab)); } } else { MessageBox.Show("Проверьте соединение перед выполнением операции!"); } }
public void RestoreFunc() { if (InfoTab.AppState != AppStates.Awaiting) { InfoTab = new InfoTabViewItem(AppStates.IsBusy); OnPropertyChanged(nameof(InfoTab)); try { using (SqlConnection connection = new SqlConnection(ConnectionStringModel.ConnectionString)) { var commandText = $@"RESTORE DATABASE {ConnectionStringModel.DbNameText} FROM DISK = '{ConnectionStringModel.PathText}'"; var command = new SqlCommand(commandText, connection); command.CommandText = commandText; command.CommandTimeout = 3000; connection.Open(); command.ExecuteNonQuery(); } if (Settings.Default.Paths != null) { if (!Settings.Default.Paths.Contains(ConnectionStringModel.PathText) && !string.IsNullOrEmpty(ConnectionStringModel.PathText)) { Settings.Default.Paths.Add(ConnectionStringModel.PathText); Settings.Default.Save(); } } else { Settings.Default.Paths = new System.Collections.Specialized.StringCollection(); Settings.Default.Paths.Add(ConnectionStringModel.PathText); Settings.Default.Save(); } InfoTab = new InfoTabViewItem(AppStates.SuccessfullyRestored); OnPropertyChanged(nameof(InfoTab)); } catch (Exception ex) { Clipboard.SetText(ex.Message); InfoTab = new InfoTabViewItem(AppStates.RestoreError); OnPropertyChanged(nameof(InfoTab)); } } else { MessageBox.Show("Проверьте соединение перед выполнением операции!"); } }
public static BitmapSource Get() { if (Clipboard.ContainsImage() && Clipboard.GetImage() is Bitmap bitmap) { using (var ms = new MemoryStream()) { bitmap.Save(ms, ImageFormat.Png); return(BitmapDecoder.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames[0]); } } return(null); }
private void ContextMenu_Opened(object sender, RoutedEventArgs e) { if (sender is ContextMenu ctxtMenu && ctxtMenu.PlacementTarget is ListView lstView && lstView.Parent is Grid grd && grd.Parent is FileList flList) { F_PasteMI.IsEnabled = flList.CanAdd && Clipboard.GetData("FichierCollection") is Fichier[] array && array.Length > 0; } if (sender is ContextMenu contextMenu && contextMenu.PlacementTarget is ListViewItem item && ItemsControl.ItemsControlFromItemContainer(item) is ListView listView && listView.Parent is Grid grid && grid.Parent is FileList fileList) { CutMI.IsEnabled = fileList.CanRemove; PasteMI.IsEnabled = fileList.CanAdd && Clipboard.GetData("FichierCollection") is Fichier[] array && array.Length > 0; var selectedItems = listView.SelectedItems.OfType <Fichier>(); SkipMI.IsEnabled = selectedItems.Any(fichier => fichier.IsCancellable); } }
public winMain(winSplash splash = null) { InitializeComponent(); DataContext = this; if (splash != null) { splash.InvokeUpdate("Loading application settings ..."); } _FormulaZoom = Settings.Default.FormulaScale; ClipBgColor.SelectedColor = Settings.Default.BgColorToClip; JpgBgColor.SelectedColor = Settings.Default.BgColorToJpg; if (splash != null) { splash.InvokeUpdate("Loading V8 javascipt engine ..."); } _ = MathjaxParser.GetInstance(); if (splash != null) { splash.InvokeUpdate("Loading application resouces ..."); } //InitializeFontSelector(); //formulaFontName = ((FontFamily)eFontFamily.GetFirstCheckedItem().Tag).ToString(); //formulaFontSize = (double)eFontSize.EditValue; DataObject.AddCopyingHandler(txtInputFomula, OnInputFomulaCopying); if (Clipboard.ContainsText()) { myClipboard.Add(Clipboard.GetText()); } if (splash != null) { splash.InvokeUpdate("Loading latex resources ..."); } LoadSymbols(); if (splash != null) { splash.InvokeUpdate("Show window ..."); } AddNotifiactions(); Application.Current.Exit += OnApplicationExit; }
public override bool MatchesClipboard() { if (Clipboard.ContainsFileDropList()) { StringCollection clipboardFileDropList = Clipboard.GetFileDropList(); if (clipboardFileDropList.Count == fileDropList.Count) { foreach (string filepath in fileDropList) { if (!clipboardFileDropList.Contains(filepath)) { return(false); } } return(true); } } return(false); }
public override void OnExecute(CommandEventArgs e) { foreach (ISvnRepositoryItem i in e.Selection.GetSelection <ISvnRepositoryItem>()) { if (i.Uri != null) { Clipboard.SetText(i.Uri.AbsoluteUri); } return; } foreach (SvnItem item in e.Selection.GetSelectedSvnItems(false)) { if (item.Uri != null) { Clipboard.SetText(item.Uri.AbsoluteUri); } return; } }
/// <summary> /// Saves the given text to the clipboard /// </summary> public static void Save(string text) { ExceptionDispatchInfo exceptionDispatchInfo = null; var thread = new Thread(() => { try { WinFormsClipboard.SetText(text); } catch (Exception exception) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); exceptionDispatchInfo?.Throw(); }
public GLTextBox(GLGui gui) : base(gui) { Render += OnRender; MouseDown += OnMouseDown; MouseUp += OnMouseUp; MouseEnter += OnMouseEnter; MouseLeave += OnMouseLeave; MouseMove += OnMouseMove; Focus += OnFocus; FocusLost += OnFocusLost; KeyDown += OnKeyDown; KeyPress += OnKeyPress; skinEnabled = Gui.Skin.TextBoxEnabled; skinActive = Gui.Skin.TextBoxActive; skinHover = Gui.Skin.TextBoxHover; skinDisabled = Gui.Skin.TextBoxDisabled; outer = new Rectangle(0, 0, 100, 0); ContextMenu = new GLContextMenu(gui); ContextMenu.Add(new GLContextMenuEntry(gui) { Text = "Copy" }).Click += (s, e) => { if (selectionStart.Index != cursorPosition.Index) { CopySelection(); } }; ContextMenu.Add(new GLContextMenuEntry(gui) { Text = "Paste" }).Click += (s, e) => { if (Clipboard.ContainsText()) { Insert(Clipboard.GetText()); } }; }
private void OnUIInit() { QMSingleButton CopyIDButton = new QMSingleButton( "ShortcutMenu", ButtonsX.Value, ButtonsY.Value, "Copy\nInstance ID", delegate() { Clipboard.SetText($"{RoomManager.field_Internal_Static_ApiWorld_0.id}:{RoomManager.field_Internal_Static_ApiWorldInstance_0.instanceId}"); }, "Copy the ID of the current instance." ); QMSingleButton JoinInstanceButton = new QMSingleButton( "ShortcutMenu", ButtonsX.Value, ButtonsY.Value, "Join\nInstance", delegate() { new PortalInternal().Method_Private_Void_String_String_PDM_0(Clipboard.GetText().Split(':')[0], Clipboard.GetText().Split(':')[1]); }, "Join an instance via your clipboard." ); Misc.ChangeButtonSize(CopyIDButton.getGameObject(), 420, 210); Misc.ChangeButtonSize(JoinInstanceButton.getGameObject(), 420, 210); Misc.MoveButton(CopyIDButton.getGameObject(), CopyIDButton.getGameObject().GetComponent <RectTransform>().localPosition.x, CopyIDButton.getGameObject().GetComponent <RectTransform>().localPosition.y + 105); Misc.MoveButton(JoinInstanceButton.getGameObject(), JoinInstanceButton.getGameObject().GetComponent <RectTransform>().localPosition.x, JoinInstanceButton.getGameObject().GetComponent <RectTransform>().localPosition.y - 105); }
/// <summary> /// Copy data from Clipboard and put on grid. /// /// Currently ReoGrid supports the following types of source from the clipboard. /// - Data from another ReoGrid instance /// - Plain/Unicode Text from any Windows Applications /// - Tabbed Plain/Unicode Data from Excel or similar applications /// /// When data copied from another ReoGrid instance, and the destination range /// is bigger than the source, ReoGrid will try to repeat putting data to fill /// the destination range entirely. /// /// Todo: Copy border and cell style from Excel. /// </summary> public bool Paste() { if (IsEditing) { this.controlAdapter.EditControlPaste(); } else { // Paste method will always perform action to do paste // do nothing if in readonly mode if (this.HasSettings(WorksheetSettings.Edit_Readonly) // or selection is empty || this.selectionRange.IsEmpty) { return(false); } try { this.controlAdapter.ChangeCursor(CursorStyle.Busy); PartialGrid partialGrid = null; string clipboardText = null; #if WINFORM || WPF DataObject data = Clipboard.GetDataObject() as DataObject; if (data != null) { partialGrid = data.GetData(ClipBoardDataFormatIdentify) as PartialGrid; if (data.ContainsText()) { clipboardText = data.GetText(); } } #elif ANDROID #endif // WINFORM || WPF if (partialGrid != null) { #region Partial Grid Pasting int startRow = selectionRange.Row; int startCol = selectionRange.Col; int rows = partialGrid.Rows; int cols = partialGrid.Columns; int rowRepeat = 1; int colRepeat = 1; if (selectionRange.Rows % partialGrid.Rows == 0) { rows = selectionRange.Rows; rowRepeat = selectionRange.Rows / partialGrid.Rows; } if (selectionRange.Cols % partialGrid.Columns == 0) { cols = selectionRange.Cols; colRepeat = selectionRange.Cols / partialGrid.Columns; } var targetRange = new RangePosition(startRow, startCol, rows, cols); if (!RaiseBeforePasteEvent(targetRange)) { return(false); } if (targetRange.EndRow >= this.rows.Count || targetRange.EndCol >= this.cols.Count) { // TODO: paste range overflow // need to notify user-code to handle this return(false); } // check whether the range to be pasted contains readonly cell if (this.CheckRangeReadonly(targetRange)) { this.NotifyExceptionHappen(new OperationOnReadonlyCellException("specified range contains readonly cell")); return(false); } // check any intersected merge-range in partial grid // bool cancelPerformPaste = false; if (partialGrid.Cells != null) { try { #region Check repeated intersected ranges for (int rr = 0; rr < rowRepeat; rr++) { for (int cc = 0; cc < colRepeat; cc++) { partialGrid.Cells.Iterate((row, col, cell) => { if (cell.IsMergedCell) { for (int r = startRow; r < cell.MergeEndPos.Row - cell.InternalRow + startRow + 1; r++) { for (int c = startCol; c < cell.MergeEndPos.Col - cell.InternalCol + startCol + 1; c++) { int tr = r + rr * partialGrid.Rows; int tc = c + cc * partialGrid.Columns; var existedCell = cells[tr, tc]; if (existedCell != null) { if ( // cell is a part of merged cell (existedCell.Rowspan == 0 && existedCell.Colspan == 0) // cell is merged cell || existedCell.IsMergedCell) { throw new RangeIntersectionException(selectionRange); } // cell is readonly else if (existedCell.IsReadOnly) { throw new CellDataReadonlyException(cell.InternalPos); } } } } } return(Math.Min(cell.Colspan, (short)1)); }); } } #endregion // Check repeated intersected ranges } catch (Exception ex) { cancelPerformPaste = true; // raise event to notify user-code there is error happened during paste operation if (OnPasteError != null) { OnPasteError(this, new RangeOperationErrorEventArgs(selectionRange, ex)); } } } if (!cancelPerformPaste) { DoAction(new SetPartialGridAction(new RangePosition( startRow, startCol, rows, cols), partialGrid)); } #endregion // Partial Grid Pasting } else if (!string.IsNullOrEmpty(clipboardText)) { #region Plain Text Pasting var arrayData = RGUtility.ParseTabbedString(clipboardText); int rows = Math.Max(selectionRange.Rows, arrayData.GetLength(0)); int cols = Math.Max(selectionRange.Cols, arrayData.GetLength(1)); var targetRange = new RangePosition(selectionRange.Row, selectionRange.Col, rows, cols); if (!RaiseBeforePasteEvent(targetRange)) { return(false); } if (this.controlAdapter != null) { var actionSupportedControl = this.controlAdapter.ControlInstance as IActionControl; if (actionSupportedControl != null) { actionSupportedControl.DoAction(this, new SetRangeDataAction(targetRange, arrayData)); } } #endregion // Plain Text Pasting } } catch (Exception ex) { // raise event to notify user-code there is error happened during paste operation //if (OnPasteError != null) //{ // OnPasteError(this, new RangeOperationErrorEventArgs(selectionRange, ex)); //} this.NotifyExceptionHappen(ex); } finally { this.controlAdapter.ChangeCursor(CursorStyle.Selection); RequestInvalidate(); } if (AfterPaste != null) { AfterPaste(this, new RangeEventArgs(this.selectionRange)); } } return(true); }
/// <summary> /// Copy data and put into Clipboard. /// </summary> public bool Copy() { if (IsEditing) { this.controlAdapter.EditControlCopy(); } else { this.controlAdapter.ChangeCursor(CursorStyle.Busy); try { if (BeforeCopy != null) { var evtArg = new BeforeRangeOperationEventArgs(selectionRange); BeforeCopy(this, evtArg); if (evtArg.IsCancelled) { return(false); } } #if EX_SCRIPT var scriptReturn = RaiseScriptEvent("oncopy"); if (scriptReturn != null && !ScriptRunningMachine.GetBoolValue(scriptReturn)) { return(false); } #endif // EX_SCRIPT // highlight current copy range currentCopingRange = selectionRange; #if WINFORM || WPF DataObject data = new DataObject(); data.SetData(ClipBoardDataFormatIdentify, GetPartialGrid(currentCopingRange, PartialGridCopyFlag.All, ExPartialGridCopyFlag.None, true)); string text = StringifyRange(currentCopingRange); if (!string.IsNullOrEmpty(text)) { data.SetText(text); } // set object data into clipboard Clipboard.SetDataObject(data); #endif // WINFORM || WPF if (AfterCopy != null) { AfterCopy(this, new RangeEventArgs(this.selectionRange)); } } catch (Exception ex) { this.NotifyExceptionHappen(ex); return(false); } finally { this.controlAdapter.ChangeCursor(CursorStyle.PlatformDefault); } } return(true); }
private static void c_Executing(object sender, CommandExecutingEventArgs e) { Window aw = Window.ActiveWindow; // section plane. It is not null only if sketch or section mode is on. Plane sP = aw.ActiveContext.SectionPlane; if (sP != null) { int sw = aw.Size.Width; int sh = aw.Size.Height; // get screen center, right-mid and upper mid System.Drawing.Point sm = new System.Drawing.Point((int)Math.Round(sw * 0.5), (int)Math.Round(sh * 0.5)); System.Drawing.Point sr = new System.Drawing.Point(sw, sm.Y); System.Drawing.Point su = new System.Drawing.Point(sm.X, 1); // screen center projection onto section plane in model coordinates Point mm; if (sP.TryIntersectLine(aw.ActiveContext.GetCursorRay(sm), out mm)) { // get projections of right mid and upper mid and use these projections // to define bas vectors. Point mr, mu; sP.TryIntersectLine(aw.ActiveContext.GetCursorRay(sr), out mr); sP.TryIntersectLine(aw.ActiveContext.GetCursorRay(su), out mu); Vector bx = mr - mm; Vector bz = Vector.Cross(bx, mu - mm); // normal to section plane looking to us Vector by = Vector.Cross(bz, bx); double ext = bx.Magnitude; // rotate view to look perpendicular to section plane double fe = ext * Math.Min(sw, sh) / Math.Max(sw, sh) * 2; aw.SetProjection(Frame.Create(mm, bx.Direction, by.Direction), fe); // generate string for clipboard string f3 = " {0:G5} {1:G5} {2:G5} "; string f1 = " {0:G5} "; string pc = ""; // or command pc = "or"; pc += string.Format(f3, nullify(mm.X * cc), nullify(mm.Y * cc), nullify(mm.Z * cc)); // bas command bx = bx.Direction.UnitVector; by = by.Direction.UnitVector; pc += "bas"; pc += string.Format(f3, nullify(bx.X), nullify(bx.Y), nullify(bx.Z)); pc += string.Format(f3, nullify(by.X), nullify(by.Y), nullify(by.Z)); // ext command pc += "ext"; pc += string.Format(f1, ext * cc); // tune formatting pc = pc.Replace(",", "."); pc = pc.Replace("E+000", " "); pc = pc.Replace("E-000", " "); pc = pc.Replace("E+00", "E+"); pc = pc.Replace("E-00", "E-"); pc = pc.Replace("E+0", "E+"); pc = pc.Replace("E-0", "E-"); // put to clipboard ClipBoard.SetText(pc); } else { SpaceClaim.Api.V16.Application.ReportStatus("Section plane exists but cannot intersect with cursor ray", StatusMessageType.Information, null); } } else { // try to read plot commands from clipboard Frame fr; double ext; if (TryParseClipboard(out fr, out ext)) { // If clipboard parsed, add a new plane to the model DatumPlane.Create(aw.Document.MainPart, "MCNP plot plane", Plane.Create(fr)); } else { SpaceClaim.Api.V16.Application.ReportStatus("Clipboard does not contain MCNP plot commands.", StatusMessageType.Warning, null); } } }
private static bool TryParseClipboard(out Frame fr, out double ext) { if (ClipBoard.ContainsText()) { string cmd = ClipBoard.GetText().ToLower(); while (cmd.Contains(" ")) { cmd = cmd.Replace(" ", " "); // remove repeated spaces } List <string> tokens = cmd.Split(null).ToList(); // list elements can be removed. bool edef = false; // flags that ext, bas and or are defined from clipboard. bool bdef = false; bool odef = false; Point mm; Vector bx, by; double e1 = 0; while (tokens.Count > 0) { SpaceClaim.Api.V16.Application.ReportStatus(string.Format("Parsing token {0} from {1}", tokens[0], tokens.Count), StatusMessageType.Information, null); if (tokens[0].Contains("or")) { double x = float.Parse(tokens[1], CultureInfo.InvariantCulture.NumberFormat); double y = float.Parse(tokens[2], CultureInfo.InvariantCulture.NumberFormat); double z = float.Parse(tokens[3], CultureInfo.InvariantCulture.NumberFormat); tokens.RemoveAt(0); tokens.RemoveAt(0); tokens.RemoveAt(0); tokens.RemoveAt(0); odef = true; mm = Point.Create(x / cc, y / cc, z / cc); SpaceClaim.Api.V16.Application.ReportStatus(string.Format("Parsed or: {0}, {1}, {2}", x, y, z), StatusMessageType.Information, null); } else if (tokens[0].Contains("bas")) { tokens.RemoveAt(0); var vals = new List <Double> { }; for (int i = 1; i <= 6; i++) { vals.Add(float.Parse(tokens[0], CultureInfo.InvariantCulture.NumberFormat)); SpaceClaim.Api.V16.Application.ReportStatus(string.Format("Parsed bas: {0}, {1}", tokens[0], vals.Last()), StatusMessageType.Information, null); tokens.RemoveAt(0); } bx = Vector.Create(vals[0], vals[1], vals[2]); by = Vector.Create(vals[3], vals[4], vals[5]); bdef = true; } else if (tokens[0].Contains("ext")) { // use only the first entry here e1 = float.Parse(tokens[1], CultureInfo.InvariantCulture.NumberFormat); tokens.RemoveAt(0); tokens.RemoveAt(0); edef = true; SpaceClaim.Api.V16.Application.ReportStatus(string.Format("Parsed ext: {0}", e1), StatusMessageType.Information, null); } else { tokens.RemoveAt(0); } } if (odef && bdef && edef) { fr = Frame.Create(mm, bx.Direction, by.Direction); ext = e1 / cc; SpaceClaim.Api.V16.Application.ReportStatus("ClipBoard parsed.", StatusMessageType.Information, null); return(true); } else { fr = Frame.Create(mm, Vector.Create(0, 0, 1).Direction); ext = 0.0; return(false); } } throw new NotImplementedException(); }
public static async Task <bool> ReadAloud(FunctionArgs args) { string action = args["action"]; switch (action) { case "pause": App.Current.Logger.LogError("ReadAloud: pause not supported"); break; case "stop": case "play": Functions.speechPlayer?.Stop(); Functions.speechPlayer?.Dispose(); Functions.speechPlayer = null; if (action == "stop") { break; } App.Current.Logger.LogDebug("ReadAloud: Storing clipboard"); IDataObject?clipboardData = Clipboard.GetDataObject(); Dictionary <string, object?>?dataStored = null; if (clipboardData != null) { dataStored = clipboardData.GetFormats() .ToDictionary(format => format, format => (object?)clipboardData.GetData(format, false)); } Clipboard.Clear(); // Get the selection App.Current.Logger.LogDebug("ReadAloud: Getting selected text"); await SelectionReader.Default.GetSelectedText(System.Windows.Forms.SendKeys.SendWait); string text = Clipboard.GetText(); // Restore the clipboard App.Current.Logger.LogDebug("ReadAloud: Restoring clipboard"); Clipboard.Clear(); dataStored?.Where(kv => kv.Value != null).ToList() .ForEach(kv => Clipboard.SetData(kv.Key, kv.Value)); // Talk the talk SpeechSynthesizer synth = new SpeechSynthesizer(); SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text); speechPlayer = new SoundPlayer(stream.AsStream()); speechPlayer.LoadCompleted += (o, args) => { speechPlayer.Play(); }; speechPlayer.LoadAsync(); break; } return(true); }
private void CopyVersion() { var version = $"{Channel} - ({ typeof(AboutWindow).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion})"; Clipboard.SetText(version); }
private void CopyFPMI(object sender, RoutedEventArgs e) { AskingFile fsender = (((ContextMenu)(sender as MenuItem).Parent).PlacementTarget as ListViewItem).Content as AskingFile; Threading.MultipleAttempts(() => { Clipboard.SetText("\"" + fsender.Name + "\""); }, throwEx: false); }
private void CopyFPMI(object sender, RoutedEventArgs e) { string ssender = (((ContextMenu)(sender as MenuItem).Parent).PlacementTarget as ListBoxItem).Content as string; Threading.MultipleAttempts(() => { Clipboard.SetText("\"" + ssender + "\""); }, throwEx: false); }