public object GetData(TransferDataType type) { if (type == null) { throw new ArgumentNullException("type"); } while (!IsTypeAvailable(type)) { Thread.Sleep(1); } if (type == TransferDataType.Image) { return(WindowsClipboard.GetImage()); } if (type == TransferDataType.Rtf) { return(WindowsClipboard.GetText(TextDataFormat.Rtf)); } if (type == TransferDataType.Text) { if (WindowsClipboard.ContainsText(TextDataFormat.UnicodeText)) { return(WindowsClipboard.GetText()); } return(WindowsClipboard.GetText(TextDataFormat.Text)); } throw new NotImplementedException(); }
private void CheckMagnetLinks() { try { var visibility = Visibility.Collapsed; if (Clipboard.ContainsText()) { var text = Clipboard.GetText(); if (IgnoredClipboardValue != text) { if (Uri.IsWellFormedUriString(text, UriKind.Absolute)) { var uri = new Uri(text); if (uri.Scheme == "magnet") { try { var link = new MagnetLink(text); if (!Client.Torrents.Any(t => t.Torrent.InfoHash == link.InfoHash)) { quickAddName.Text = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(link.Name)); visibility = Visibility.Visible; } } catch { } } } } } quickAddGrid.Visibility = visibility; } catch { /* This is basically the least important feature, we can afford to just ditch the exception */ } }
private void ImportLrcFromClipboardWithoutTime(object sender, RoutedEventArgs e) { string content = Clipboard.GetText(); lrcManager.LoadFromStringWithoutTime(content); UpdateListBox(); }
private string GetClipboardContent() { if (WinClipboard.ContainsText()) { return(WinClipboard.GetText()); } // ReSharper disable once InvertIf if (WinClipboard.ContainsImage()) { MemoryStream imageStream = (MemoryStream)WinClipboard.GetData(DataFormats.Dib); BitmapSource imageBitmap = DibToBitmapConverter.Read(imageStream); if (imageBitmap == null) { Logger.Error("Unable to create bitmap from image copied into the clipboard!"); return(null); } using (MemoryStream rawImage = new MemoryStream()) { BitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(imageBitmap)); encoder.Save(rawImage); return($"{pngImageHeader}{Convert.ToBase64String(rawImage.ToArray())}"); } } return(null); }
public void TextContaningNoTabIsPasedIntoAnIntellisenseTextBoxExpectedTabInsertedEventNotRaised() { var preserveClipboard = Clipboard.GetText(); try { bool eventRaised = false; EventManager.RegisterClassHandler(typeof(IntellisenseTextBox), IntellisenseTextBox.TabInsertedEvent, new RoutedEventHandler((s, e) => { eventRaised = true; })); Clipboard.SetText("Cake"); IntellisenseTextBox textBox = new IntellisenseTextBox(); textBox.CreateVisualTree(); textBox.Paste(); Assert.IsFalse(eventRaised, "The 'IntellisenseTextBox.TabInsertedEvent' was raised when text that didn't contain a tab was pasted into the IntellisenseTextBox."); } finally { Clipboard.SetText(preserveClipboard); } }
public void AddFirstJumper() { if (CanAddFirstJumper is false) { return; } if (int.TryParse(Clipboard.GetText(), out var time) is false) { return; } var jumper = new Jumper { JumperMode = JumperMode.Skip, Number = Jumpers.Count + 1, StartTime = new TimeSpan(), EndTime = TimeSpan.FromMilliseconds(time), Film = EEVM.ESVM.SelectedFilm, Season = EEVM.ESVM.SelectedSeason, Episode = EEVM.CurrentEpisode, AddressInfo = EEVM.SelectedAddressInfo }; InsertEntityToDb(jumper); Jumpers = new BindableCollection <Jumper>(CurrentAddressInfo.Jumpers); RefreshJumpersConfig(); NotifyOfPropertyChange(() => CanAddFirstJumper); }
private void MainWindow_OnActivated(object sender, EventArgs e) { if (FirstTimeActivated) { FirstTimeActivated = false; var allAssemblies = new List <LeagueSharpAssembly>(); foreach (var profile in Config.Instance.Profiles) { allAssemblies.AddRange(profile.InstalledAssemblies); } allAssemblies = allAssemblies.Distinct().ToList(); PrepareAssemblies(allAssemblies, Config.Instance.FirstRun || Config.Instance.UpdateOnLoad, true); } var text = Clipboard.GetText(); if (text.StartsWith(LSUriScheme.FullName)) { Clipboard.SetText(""); LSUriScheme.HandleUrl(text, this); } }
public void RemoteServerUITests_EditRemoteWebSource_WebSourceIsEdited() { const string TextToSearchWith = "Dev2GetCountriesWebService"; //Edit remote web source ExplorerUIMap.DoubleClickSource(TextToSearchWith, "WEB SRC", RemoteServerName); var actualLeftTitleText = WebSourceWizardUIMap.GetLeftTitleText(); var actualRightTitleText = WebSourceWizardUIMap.GetRightTitleText(); Assert.AreEqual("Edit - Dev2GetCountriesWebService", actualLeftTitleText); Assert.AreEqual(remoteConnectionString, actualRightTitleText); WebSourceWizardUIMap.EnterTextIntoWizardTextBox(3, "?extension=json&prefix=b"); WebSourceWizardUIMap.PressButtonOnWizard(3); SaveDialogUIMap.ClickSave(); //Change it back ExplorerUIMap.DoubleClickSource(TextToSearchWith, "WEB SRC", RemoteServerName); //Get textbox text var persistClipboard = Clipboard.GetText(); KeyboardCommands.SendTabs(3); WebSourceWizardUIMap.PressCtrlC(); WebSourceWizardUIMap.EnterTextIntoWizardTextBox(0, "?extension=json&prefix=a"); WebSourceWizardUIMap.PressButtonOnWizard(3); string query = Clipboard.GetText(); Clipboard.SetText(persistClipboard); SaveDialogUIMap.ClickSave(); Assert.AreEqual("?extension=json&prefix=b", query, "Cannot change remote web source"); }
private void onCopyPasteReceived() { if (!m_isReceivingShortcuts) { return; } Application.Current.Dispatcher.InvokeAsync(() => { try { var cpContent = Clipboard.GetText(); var output = ProcessInput(cpContent); if (output == null) { return; } inputText.Text = cpContent; SetOutputText(output); var move = moveCheckbox.IsChecked ?? false; if (move) { var cursorPos = GetCursorPos(); Left = cursorPos.X - this.Width / 2; if (cursorPos.Y - this.Height / 2 < 0) { this.Top = 0; } else { Top = cursorPos.Y - this.Height / 2; } Activate(); } var toClipboard = this.toClipboard.IsChecked ?? false; if (toClipboard) { Clipboard.SetText(output); Mediator.Send(new ShowNotificationCommand { Message = "Pretty print successful!" }); } } catch (Exception e) { ShowErrorMessage(e.Message); } }); }
private void MainWindow_OnActivated(object sender, EventArgs e) { var text = Clipboard.GetText(); if (text.StartsWith(LSUriScheme.FullName)) { Clipboard.SetText(""); LSUriScheme.HandleUrl(text, this); } }
public static IEnumerable <string> ClipBoardStrs() { if (!Clipboard.ContainsText()) { return(new string[0]); } string txt = Clipboard.GetText(); string[] cells = txt.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); return(cells); }
public void PasteBlockStyle(IItemFilterBlockViewModel targetBlockViewModel) { var clipboardText = Clipboard.GetText(); if (string.IsNullOrEmpty(clipboardText)) { return; } _blockTranslator.ReplaceColorBlockItemsFromString(targetBlockViewModel.Block.BlockItems, clipboardText); targetBlockViewModel.RefreshBlockPreview(); }
private IntPtr WinProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { switch (msg) { case Win32.WmChangecbchain: if (wParam == hWndNextViewer) { hWndNextViewer = lParam; //clipboard viewer chain changed, need to fix it. } else if (hWndNextViewer != IntPtr.Zero) { Win32.SendMessage(hWndNextViewer, msg, wParam, lParam); //pass the message to the next viewer. } break; case Win32.WmDrawclipboard: Task.Run(async() => { await mainWindow.Dispatcher.InvokeAsync(async() => { Win32.SendMessage(hWndNextViewer, msg, wParam, lParam); //pass the message to the next viewer //clipboard content changed if (Clipboard.ContainsText() && !string.IsNullOrEmpty(Clipboard.GetText().Trim())) { var currentText = Clipboard.GetText().RemoveSpecialCharacters().ToLowerInvariant(); if (!string.IsNullOrEmpty(currentText)) { await Task.Run(async() => { if (cancellationTokenSource.Token.IsCancellationRequested) { return; } await WhenClipboardContainsTextEventHandler.InvokeSafelyAsync(this, new WhenClipboardContainsTextEventArgs { CurrentString = currentText } ); await FlushCopyCommandAsync(); }); } } }, DispatcherPriority.Background); }); break; } return(IntPtr.Zero); }
public void RemoteServerUITests_EditRemoteEmailSource_EmailSourceIsEdited() { var emailServer = TestUtils.StartEmailServer(); var machineName = Environment.MachineName; const string TextToSearchWith = "EmailSource"; //Edit remote email source ExplorerUIMap.DoubleClickSource(TextToSearchWith, "REMOTETESTS", RemoteServerName); var actualLeftTitleText = EmailSourceWizardUIMap.GetLeftTitleText(); var actualRightTitleText = EmailSourceWizardUIMap.GetRightTitleText(); Assert.AreEqual("Edit - EmailSource", actualLeftTitleText); Assert.AreEqual(remoteConnectionString, actualRightTitleText); //Change Timeout EmailSourceWizardUIMap.EnterTextIntoWizardTextBox(1, machineName); EmailSourceWizardUIMap.EnterTextIntoWizardTextBox(5, "1234"); //Test Email Source EmailSourceWizardUIMap.PressButtonOnWizard(1, 1000); EmailSourceWizardUIMap.EnterTextIntoWizardTextBox(0, "@gmail.com"); EmailSourceWizardUIMap.EnterTextIntoWizardTextBox(1, "*****@*****.**"); EmailSourceWizardUIMap.PressButtonOnWizard(1, 5000); EmailSourceWizardUIMap.PressButtonOnWizard(8); SaveDialogUIMap.ClickSave(); //Change it back ExplorerUIMap.DoubleClickSource(TextToSearchWith, "REMOTETESTS", RemoteServerName); //Get the Timeout text var persistClipboard = Clipboard.GetText(); EmailSourceWizardUIMap.SendTabsForWizard(6); EmailSourceWizardUIMap.PressCtrlC(); EmailSourceWizardUIMap.EnterTextIntoWizardTextBox(0, "100"); EmailSourceWizardUIMap.PressButtonOnWizard(1); string timeout = Clipboard.GetText(); Clipboard.SetText(persistClipboard); //Test Email Source EmailSourceWizardUIMap.EnterTextIntoWizardTextBox(0, "@gmail.com"); EmailSourceWizardUIMap.EnterTextIntoWizardTextBox(1, "*****@*****.**"); EmailSourceWizardUIMap.PressButtonOnWizard(1, 5000); EmailSourceWizardUIMap.PressButtonOnWizard(8); SaveDialogUIMap.ClickSave(); //Assert remote email source changed its timeout Assert.AreEqual("1234", timeout, "Cannot edit remote email source"); TestUtils.StopEmailServer(emailServer); }
public void PasteFilmEndTime() { if (CanPasteFilmEndTime is false) { return; } if (int.TryParse(Clipboard.GetText(), out var time)) { CurrentAddressInfo.FilmEndTime = TimeSpan.FromMilliseconds(time); NotifyOfPropertyChange(() => CurrentAddressInfo); NotifyChanges(); } }
public void PasteEndTime() { if (CanPasteEndTime is false) { return; } if (int.TryParse(Clipboard.GetText(), out var time)) { SelectedJumper.EndTime = TimeSpan.FromMilliseconds(time); NotifyOfPropertyChange(() => SelectedJumper); NotifyChanges(); } }
public NewDownload(NewDownloadViewModel downloadViewModel) { InitializeComponent(); _downloadManager = DownloadManager.GetInstance(); DestinationPath.Text = KnownFolders.GetPath(KnownFolder.Downloads); var urlstr = Clipboard.GetText(); if (Uri.IsWellFormedUriString(urlstr, UriKind.RelativeOrAbsolute)) { FilePath.Text = urlstr; } DataContext = downloadViewModel; }
private void SendEmail() { HandleException(() => { string emailText = Clipboard.GetText(); LogEmail(emailText); _sender.SendAsync(emailText) .ContinueWith( (t, state) => LogError(t.Exception?.GetBaseException()), null, CancellationToken.None, TaskContinuationOptions.NotOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext()); }); }
private async Task <bool> CheckClipboardForNetDeckImport() { try { if (Clipboard.ContainsText()) { var clipboardContent = Clipboard.GetText(); if (clipboardContent.StartsWith("netdeckimport")) { var clipboardLines = clipboardContent.Split('\n').ToList(); var deckName = clipboardLines.FirstOrDefault(line => line.StartsWith("name:")); if (!string.IsNullOrEmpty(deckName)) { clipboardLines.Remove(deckName); deckName = deckName.Replace("name:", "").Trim(); } var url = clipboardLines.FirstOrDefault(line => line.StartsWith("url:")); if (!string.IsNullOrEmpty(url)) { clipboardLines.Remove(url); url = url.Replace("url:", "").Trim(); } clipboardLines.RemoveAt(0); //"netdeckimport" var deck = ParseCardString(clipboardLines.Aggregate((c, n) => c + "\n" + n)); if (deck != null) { deck.Url = url; deck.Note = url; deck.Name = deckName; SetNewDeck(deck); if (Config.Instance.AutoSaveOnImport) { await SaveDeckWithOverwriteCheck(); } ActivateWindow(); } Clipboard.Clear(); return(true); } } } catch (Exception e) { Logger.WriteLine(e.ToString()); return(false); } return(false); }
private void MainWindow_OnActivated(object sender, EventArgs e) { if (FirstTimeActivated) { FirstTimeActivated = false; PrepareAssemblies(Config.SelectedProfile.InstalledAssemblies, Config.FirstRun || Config.UpdateOnLoad, true); } var text = Clipboard.GetText(); if (text.StartsWith(LSUriScheme.FullName)) { Clipboard.SetText(""); LSUriScheme.HandleUrl(text, this); } }
/// <summary> /// Copies a string to the clipboard. If it still exists on the clipboard after the amount of time /// specified in <paramref name="timeout"/>, it will be removed again. /// </summary> /// <param name="value">The text to add to the clipboard.</param> /// <param name="timeout">The amount of time, in seconds, the text should remain on the clipboard.</param> private void CopyToClipboard(string value, double timeout) { if (InvokeRequired) { Invoke(new Action <string, double>(CopyToClipboard), value, timeout); return; } // Try to save the current contents of the clipboard and restore them after the password is removed. var previousText = ""; if (Clipboard.ContainsText()) { Log.Send("Saving previous clipboard contents before storing the password"); previousText = Clipboard.GetText(); } //Clipboard.SetText(value); try { Clipboard.SetDataObject(value); } catch (Exception e) { Log.Send($"Password could not be copied to clipboard: {e.GetType().Name}: {e.Message}", LogLevel.Error); ShowErrorWindow($"Failed to copy your password to the clipboard ({e.GetType().Name}: {e.Message})."); } Task.Delay(TimeSpan.FromSeconds(timeout)).ContinueWith(_ => { Invoke((MethodInvoker)(() => { try { // Only reset the clipboard to its previous contents if it still contains the text we copied to it. // If the clipboard did not previously contain any text, it is simply cleared. if (Clipboard.ContainsText() && Clipboard.GetText() == value) { Log.Send("Restoring previous clipboard contents"); Clipboard.SetText(previousText); } } catch (Exception e) { Log.Send($"Failed to restore previous clipboard contents ({previousText.Length} chars): An exception occurred ({e.GetType().Name}: {e.Message})", LogLevel.Error); } })); }); }
private void DataGridPasteCommand_Execute(object sender, ExecutedRoutedEventArgs e) { DataGrid dg = sender as DataGrid; if (dg == null) { return; } CharacterViewModel model = dg.DataContext as CharacterViewModel; if (model == null) { return; } ClipboardHelper.SetAttributesString(Clipboard.GetText(), model.Character); e.Handled = true; }
private void OnPasteTranslationsMenuItemClick(object sender, RoutedEventArgs e) { var text = Clipboard.GetText(); var lines = text.Split('\n').Select(x => x.Trim('\r').Trim()).ToList(); var selectedWords = WordsDataGrid.SelectedItems.OfType <WordInfo>().ToList(); if (selectedWords.Count != lines.Count) { MessageBox.Show("Count of pasted translations is not equal to selected rows.", "Translations are not valid", MessageBoxButton.OK, MessageBoxImage.Warning); return; } for (var i = 0; i < lines.Count; i++) { selectedWords[i].TranslatedWord = lines[i]; } }
public void PasteBlock(IItemFilterBlockViewModel targetBlockViewModel) { try { var clipboardText = Clipboard.GetText(); if (clipboardText.IsNullOrEmpty()) { return; } var translatedBlock = _blockTranslator.TranslateStringToItemFilterBlock(clipboardText, Script.ThemeComponents); if (translatedBlock == null) { return; } var vm = _itemFilterBlockViewModelFactory.Create(); vm.Initialise(translatedBlock, this); if (ItemFilterBlockViewModels.Count > 0) { Script.ItemFilterBlocks.Insert(Script.ItemFilterBlocks.IndexOf(targetBlockViewModel.Block) + 1, translatedBlock); ItemFilterBlockViewModels.Insert(ItemFilterBlockViewModels.IndexOf(targetBlockViewModel) + 1, vm); } else { Script.ItemFilterBlocks.Add(translatedBlock); ItemFilterBlockViewModels.Add(vm); } SelectedBlockViewModel = vm; IsDirty = true; } catch (Exception e) { _logger.Error(e); _messageBoxService.Show("Paste Error", e.Message + Environment.NewLine + e.StackTrace + Environment.NewLine + e.InnerException.Message + Environment.NewLine + e.InnerException.StackTrace, MessageBoxButton.OK, MessageBoxImage.Error); } }
private void Button_Set_Endpoint(object sender, RoutedEventArgs e) { var str = Clipboard.GetText(); // milvaneth://api.menphina.com:2020/milvaneth/ if (string.IsNullOrWhiteSpace(str) || !Uri.TryCreate(str, UriKind.Absolute, out var uri) || !uri.Scheme.Equals("milvaneth", StringComparison.InvariantCultureIgnoreCase)) { Task.Run(() => InlineLogic.EndpointSettingLogic(false)); return; } var uriWithoutScheme = Uri.SchemeDelimiter + uri.Authority + uri.PathAndQuery + uri.Fragment; var ub = new UriBuilder(Uri.UriSchemeHttps + uriWithoutScheme); br.InternalPerferredApiEntry = ub.Uri.AbsoluteUri; Task.Run(() => InlineLogic.EndpointSettingLogic(true)); }
private async void PasteButton(object sender, RoutedEventArgs e) { var pastedData = Clipboard.GetText(); string jiraRef = null; try { var pastedUri = new Uri(pastedData); var jiraUri = new Uri(ModelHelpers.Gallifrey.Settings.JiraConnectionSettings.JiraUrl); if (pastedUri.Host == jiraUri.Host) { var uriDrag = pastedUri.AbsolutePath; jiraRef = uriDrag.Substring(uriDrag.LastIndexOf("/") + 1); } } catch (Exception) { //ignored } if (string.IsNullOrWhiteSpace(jiraRef)) { jiraRef = pastedData; } if (ModelHelpers.Gallifrey.JiraConnection.DoesJiraExist(jiraRef)) { var startDate = ViewModel.TimerDates.FirstOrDefault(x => x.DateIsSelected)?.TimerDate ?? DateTime.Today; var addTimer = new AddTimer(ModelHelpers, startDate: startDate, jiraRef: jiraRef); await ModelHelpers.OpenFlyout(addTimer); if (addTimer.AddedTimer) { ModelHelpers.SetSelectedTimer(addTimer.NewTimerId); } } else { await DialogCoordinator.Instance.ShowMessageAsync(ModelHelpers.DialogContext, "Invalid Jira", $"Unable To Locate That Jira.\n\nJira Ref Pasted: '{jiraRef}'"); } }
public void CreateTableFromClipboardHtml(string html = null) { if (string.IsNullOrEmpty(html)) { html = ClipboardHelper.GetHtmlFromClipboard(); if (string.IsNullOrEmpty(html)) { html = Clipboard.GetText(); } } var parser = new TableParser(); ObservableCollection <ObservableCollection <CellContent> > data = null; if (html.Contains("<tr>")) { data = parser.ParseHtmlToData(html); } else if (html.Contains("-|-") || html.Contains("- | -") || html.Contains("")) { data = parser.ParseMarkdownToData(html); } else if (html.Contains("-|-") || html.Contains("- | -") || html.Contains("")) { data = parser.ParseMarkdownToData(html); } else if (html.Contains("-+-")) { data = parser.ParseMarkdownGridTableToData(html); } if (data == null || data.Count < 1) { AppModel.Window.ShowStatusError("No HTML Table to process found..."); return; } TableData = data; DataGridTableEditor.TableSource = TableData; }
private void DrawContent() { if (Clipboard.ContainsText()) { string text = Clipboard.GetText(); int pos = Data.IndexOf(text); if (pos != -1) { Data.RemoveAt(pos); } Data.Insert(0, text); Index = 0; if (Data.Count > MAX_COUNT) { Data.RemoveAt(Data.Count - 1); } } }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { DataContext = new DistributedJob(); try { if (!Clipboard.ContainsText(TextDataFormat.Text)) { return; } var clipboardData = Clipboard.GetText(TextDataFormat.Text); if (clipboardData.EndsWith("-status")) { ((DistributedJob)DataContext).StatusKey = clipboardData; } } catch (OutOfMemoryException) { // If clipboard content is to large, no status key is available. } }
private IntPtr MainWindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { switch (msg) { case WM_DRAWCLIPBOARD: if (_getCopyValue && Clipboard.ContainsText()) { _getCopyValue = false; var selectedText = Clipboard.GetText().Trim(); if (selectedText.Length > 1) { LblEnglish.Text = selectedText; Translate(); Clipboard.Clear(); } } // Send message along, there might be other programs listening to the copy command. SendMessage(_clipboardViewerNext, msg, wParam, lParam); break; case WM_CHANGECBCHAIN: if (wParam == _clipboardViewerNext) { _clipboardViewerNext = lParam; } else { SendMessage(_clipboardViewerNext, msg, wParam, lParam); } break; } return(IntPtr.Zero); }