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); }
private async void ClipboardNotification_ClipboardUpdate(object sender, EventArgs e) { if (Clipboard.ContainsText()) { // Delay if clipboard still open by other app await Task.Delay(10); bool done = false; for (int i = 0; i < 5 && !done; i++) { try { var clipboradData = Clipboard.GetDataObject(); StringObject newObject = null; if (clipboradData?.GetDataPresent(DataFormats.Text) ?? false) { newObject = new StringObject() { Value = clipboradData.GetData(DataFormats.Text).ToString() }; } if (newObject != null) { if (newObject.Value.Trim().Length == 0) { return; } // Clean search to get the real clipboard entrys and not just a view or results which we cant modify // window is closed after this code anyway and search is discarded ViewModel.CurrentSearch = ""; ViewModel.ClipboardEntrys.Remove(ViewModel.ClipboardEntrys.FirstOrDefault(x => x.Value == newObject.Value)); ViewModel.ClipboardEntrys.Insert(0, newObject); if (ViewModel.ClipboardEntrys.Count > ViewModel.MaxHistoryCount) { ViewModel.ClipboardEntrys.Remove(ViewModel.ClipboardEntrys.Last()); } } done = true; } catch (COMException) { // Clipboard already opened // Delay if clipboard still open by other app await Task.Delay(10); } } // Put text into clipboard from text popup if (InputTextPopup.IsOpen && done) { PutInClipboard(true, false, ViewModel.ClipboardEntrys.First().Value); } } }
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 */ } }
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(); }
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); }
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); }
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); }
/// <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); } })); }); }
public MainWindow() { InterceptCtrlCC.Start(); InterceptCtrlCC.CtrlCCPressed += (sender, b) => { if (Clipboard.ContainsText()) { Process.Start("https://www.lingvolive.com/en-us/translate/en-ru/" + Clipboard.GetText()); } }; InitializeComponent(); if (GetStartup()) { AutostartIconPath.Data = Geometry.Parse(CheckPath); } }
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. } }
public bool IsTypeAvailable(TransferDataType type) { if (type == null) { throw new ArgumentNullException("type"); } if (type == TransferDataType.Image) { return(WindowsClipboard.ContainsImage()); } if (type == TransferDataType.Text) { return(WindowsClipboard.ContainsText(TextDataFormat.UnicodeText) || WindowsClipboard.ContainsText(TextDataFormat.Text)); } if (type == TransferDataType.Rtf) { return(WindowsClipboard.ContainsText(TextDataFormat.Rtf)); } throw new NotImplementedException(); }
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); }
/// <summary> /// Handle pasting and handle images /// </summary> public void PasteOperation() { if (Clipboard.ContainsImage()) { string imagePath = null; var bmpSource = Clipboard.GetImage(); using (var bitMap = WindowUtilities.BitmapSourceToBitmap(bmpSource)) { imagePath = AddinManager.Current.RaiseOnSaveImage(bitMap); } if (!string.IsNullOrEmpty(imagePath)) { SetSelection($"![]({imagePath})"); PreviewMarkdownCallback(); // force a preview refresh return; } string initialFolder = null; if (!string.IsNullOrEmpty(MarkdownDocument.Filename) && MarkdownDocument.Filename != "untitled") { initialFolder = Path.GetDirectoryName(MarkdownDocument.Filename); } var sd = new SaveFileDialog { Filter = "Image files (*.png;*.jpg;*.gif;)|*.png;*.jpg;*.jpeg;*.gif|All Files (*.*)|*.*", FilterIndex = 1, Title = "Save Image from Clipboard as", InitialDirectory = initialFolder, CheckFileExists = false, OverwritePrompt = true, CheckPathExists = true, RestoreDirectory = true }; var result = sd.ShowDialog(); if (result != null && result.Value) { imagePath = sd.FileName; try { var ext = Path.GetExtension(imagePath)?.ToLower(); using (var fileStream = new FileStream(imagePath, FileMode.Create)) { BitmapEncoder encoder = null; if (ext == ".png") { encoder = new PngBitmapEncoder(); } else if (ext == ".jpg" || ext == ".jpeg") { encoder = new JpegBitmapEncoder(); } else if (ext == ".gif") { encoder = new GifBitmapEncoder(); } encoder.Frames.Add(BitmapFrame.Create(bmpSource)); encoder.Save(fileStream); } } catch (Exception ex) { MessageBox.Show("Couldn't copy file to new location: \r\n" + ex.Message, mmApp.ApplicationName); return; } string relPath = Path.GetDirectoryName(sd.FileName); if (initialFolder != null) { try { relPath = FileUtils.GetRelativePath(sd.FileName, initialFolder); } catch (Exception ex) { mmApp.Log($"Failed to get relative path.\r\nFile: {sd.FileName}, Path: {imagePath}", ex); } if (!relPath.StartsWith("..\\")) { imagePath = relPath; } } if (imagePath.Contains(":\\")) { imagePath = "file:///" + imagePath; } SetSelection($"![]({imagePath})"); PreviewMarkdownCallback(); // force a preview refresh } } else if (Clipboard.ContainsText()) { // just paste as is at cursor or selection SetSelection(Clipboard.GetText()); } }
public DataPackageView GetContent() { var dataPackage = new DataPackage(); if (Clipboard.ContainsImage()) { dataPackage.SetDataProvider(StandardDataFormats.Bitmap, async ct => { var bitmap = Clipboard.GetImage(); var bitmapStream = new MemoryStream(); var bitmapEncoder = new BmpBitmapEncoder(); bitmapEncoder.Frames.Add(BitmapFrame.Create(bitmap)); bitmapEncoder.Save(bitmapStream); // Letting a MemoryStream run around does not cause problems. // The GC will take care of it, just like a byte[]. return(RandomAccessStreamReference.CreateFromStream(bitmapStream.AsRandomAccessStream())); }); } if (Clipboard.ContainsText()) { // Copying significant amounts of text still makes Clipboard.GetText() slow, so // we'll still use the SetDataProvider dataPackage.SetDataProvider(StandardDataFormats.Text, async ct => { return(Clipboard.GetText()); }); } if (Clipboard.ContainsData(DataFormats.Html)) { dataPackage.SetDataProvider(StandardDataFormats.Html, async ct => { return(Clipboard.GetData(DataFormats.Html)); }); } if (Clipboard.ContainsData(DataFormats.Rtf)) { dataPackage.SetDataProvider(StandardDataFormats.Rtf, async ct => { return(Clipboard.GetData(DataFormats.Rtf)); }); } if (Clipboard.ContainsFileDropList()) { dataPackage.SetDataProvider(StandardDataFormats.StorageItems, async ct => { var list = Clipboard.GetFileDropList(); var storageItemList = new List <IStorageItem>(list.Count); foreach (var path in list) { var attr = File.GetAttributes(path); if (attr.HasFlag(global::System.IO.FileAttributes.Directory)) { storageItemList.Add(await StorageFolder.GetFolderFromPathAsync(path)); } else { storageItemList.Add(await StorageFile.GetFileFromPathAsync(path)); } } return(storageItemList); }); } return(dataPackage.GetView()); }
static void Main(string[] args) { var prog = new Program(); Options options = null; var parserResult = Parser.Default.ParseArguments <Options>(args) .WithParsed(f => { options = f; }) .WithNotParsed(f => { foreach (var error in f) { Console.WriteLine($"ERROR: {error}"); } }); if (options == null) { Thread.Sleep(5000); return; } string connectionString = ""; string outputDirectory = null; if (!string.IsNullOrWhiteSpace(options.InputFile)) { Console.WriteLine($"Specified command file: '{options.InputFile}'"); if (File.Exists(options.InputFile)) { AutoConsole = new AutoConsole(options.InputFile, options.Variables); var version = Assembly.GetExecutingAssembly().GetName().Version; if (AutoConsole.Options.Version == null || new Version(AutoConsole.Options.Version) != version) { Console.WriteLine("WARNING"); Console.WriteLine(string.Format("The current Entity Creator version ({0}) is not equals the version ({1}) you have provided.", version, AutoConsole.Options.Version)); Console.WriteLine("There might be errors or unexpected Behavor"); } } else { Console.WriteLine("The commandfile does not exist"); AutoConsole = new AutoConsole(null, new string[0]); } } else { AutoConsole = new AutoConsole(null, new string[0]); } WinConsole.WriteLine(@"Enter Connection string or type \explore to search for a server [Only MSSQL supported]"); if (Clipboard.ContainsText() && AutoConsole.Options == null) { var maybeConnection = Clipboard.GetText(TextDataFormat.Text); var strings = maybeConnection.Split(';'); var any = strings.Any(s => s.ToLower().Contains("data source=") || s.ToLower().Contains("initial catalog=")); if (any) { WinConsole.WriteLine("Use clipboard content? [(y|Enter*) | no]"); var WinConsoleKeyInfo = System.Console.ReadKey(); if (char.ToLower(WinConsoleKeyInfo.KeyChar) == 'y' || WinConsoleKeyInfo.Key == ConsoleKey.Enter) { connectionString = maybeConnection; AutoConsole.SetNextOption(connectionString); } else { connectionString = string.Empty; } } else { connectionString = string.Empty; } } else { connectionString = string.Empty; } if (string.IsNullOrEmpty(connectionString)) { do { connectionString = AutoConsole.GetNextOption(); if (connectionString == @"\explore") { SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance; WinConsole.WriteLine("Search for data Sources in current network"); var table = instance.GetDataSources(); WinConsole.WriteLine("Row count {0}", table.Rows.Count); foreach (var column in table.Columns.Cast <DataColumn>()) { WinConsole.Write(column.ColumnName + "|"); } for (int i = 0; i < table.Rows.Count; i++) { var row = table.Rows[i]; WinConsole.Write("o {0} |", i); foreach (DataColumn col in table.Columns) { WinConsole.Write(" {0} = {1} |", col.ColumnName, row[col]); } WinConsole.WriteLine("============================"); } WinConsole.WriteLine(); } } while (string.IsNullOrEmpty(connectionString) || connectionString.ToLower().Contains(@"\explore")); } try { new MsSqlCreator(options.IncludeInVsProject).CreateEntrys(connectionString, outputDirectory, string.Empty); } catch (Exception e) { WinConsole.WriteLine("Error while executing the MsSQLEntity Creator:"); WinConsole.WriteLine(e.ToString()); WinConsole.WriteLine("Press any key to stop the application"); Thread.Sleep(5000); return; } if (AutoConsole.Options == null && options.InputFile != null) { AutoConsole.SaveStorage(options.InputFile); } }
static void Main(string[] args) { var prog = new Program(); var pathToCommandSet = ""; string outputDir = ""; string connectionString = ""; if (args.Count() == 1) { pathToCommandSet = args[0]; if (File.Exists(pathToCommandSet)) { AutoConsole = new AutoConsole(pathToCommandSet); var version = Assembly.GetExecutingAssembly().GetName().Version; if (new Version(AutoConsole.Options.Version) != version) { Console.WriteLine("WARNING"); Console.WriteLine(string.Format("The current Entity Creator version ({0}) is not equals the version ({1}) you have provided.", version, AutoConsole.Options.Version)); Console.WriteLine("There might be errors or unexpected Behavor"); } } else { AutoConsole = new AutoConsole(null); } } else { AutoConsole = new AutoConsole(null); } Console.WriteLine("Enter output dir"); outputDir = AutoConsole.GetNextOption(); if (outputDir == "temp") { outputDir = Path.GetTempPath(); } if (string.IsNullOrEmpty(outputDir) || !Directory.Exists(outputDir)) { Console.WriteLine("Invalid Directory ..."); Console.ReadKey(); return; } Console.WriteLine(@"Enter Connection string or type \explore to search for a server [ToBeSupported]"); if (Clipboard.ContainsText() && AutoConsole.Options == null) { var maybeConnection = Clipboard.GetText(TextDataFormat.Text); var strings = maybeConnection.Split(';'); var any = strings.Any(s => s.ToLower().Contains("data source=") || s.ToLower().Contains("initial catalog=")); if (any) { Console.WriteLine("Use clipboard content?"); var consoleKeyInfo = Console.ReadKey(); if (char.ToLower(consoleKeyInfo.KeyChar) == 'y') { connectionString = maybeConnection; AutoConsole.SetNextOption(connectionString); } else { connectionString = string.Empty; } } else { connectionString = string.Empty; } } else { connectionString = string.Empty; } if (string.IsNullOrEmpty(connectionString)) { do { connectionString = AutoConsole.GetNextOption(); if (connectionString == @"\explore") { SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance; Console.WriteLine("Search for data Sources in current network"); var table = instance.GetDataSources(); Console.WriteLine("Row count {0}", table.Rows.Count); foreach (var column in table.Columns.Cast <DataColumn>()) { Console.Write(column.ColumnName + "|"); } for (int i = 0; i < table.Rows.Count; i++) { var row = table.Rows[i]; Console.Write("o {0} |", i); foreach (System.Data.DataColumn col in table.Columns) { Console.Write(" {0} = {1} |", col.ColumnName, row[col]); } Console.WriteLine("============================"); } Console.WriteLine(); } } while (string.IsNullOrEmpty(connectionString) || connectionString.ToLower().Contains(@"\explore")); } new MsSqlCreator().CreateEntrys(connectionString, outputDir, string.Empty); if (AutoConsole.Options == null && pathToCommandSet != null) { AutoConsole.SaveStorage(pathToCommandSet); } }