/// <summary> /// A form for token /// </summary> /// <returns>bool true if OK was pressed, false if cancel</returns> public bool ShowConfigDialog() { SettingsForm settingsForm; ILanguage lang = Language.GetInstance(); BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(DropboxPlugin.Attributes.Name, lang.GetString(LangKey.communication_wait)); try { settingsForm = new SettingsForm(this); } finally { backgroundForm.CloseDialog(); } settingsForm.AuthToken = this.DropboxAccessToken; settingsForm.UploadFormat = this.UploadFormat.ToString(); settingsForm.AfterUploadOpenHistory = this.AfterUploadOpenHistory; settingsForm.AfterUploadLinkToClipBoard = this.AfterUploadLinkToClipBoard; DialogResult result = settingsForm.ShowDialog(); if (result == DialogResult.OK) { this.DropboxAccessToken = settingsForm.AuthToken; this.UploadFormat = (OutputFormat)Enum.Parse(typeof(OutputFormat), settingsForm.UploadFormat.ToLower()); this.AfterUploadOpenHistory = settingsForm.AfterUploadOpenHistory; this.AfterUploadLinkToClipBoard = settingsForm.AfterUploadLinkToClipBoard; IniConfig.Save(); // Save DropboxAccessToken from file DropboxUtils.SaveAccessToken(); return(true); } return(false); }
private void buttonConnect_Click(object sender, EventArgs e) { button_save.Enabled = false; using (TeamProjectPicker tpp = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false)) { DialogResult result = tpp.ShowDialog(); if (result == DialogResult.OK) { textbox_tfsUrl.Text = tpp.SelectedTeamProjectCollection.Uri.ToString(); textbox_defaultProject.Text = tpp.SelectedProjects[0].Name; button_save.Enabled = true; BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(TFSPlugin.Attributes.Name, Language.GetString("tfs",LangKey.communication_wait)); try { this.BindScreen(); } finally { backgroundForm.CloseDialog(); } } } }
private void deletePicture() { if (listview_TFS_uploads.SelectedItems != null && listview_TFS_uploads.SelectedItems.Count > 0) { for (int i = 0; i < listview_TFS_uploads.SelectedItems.Count; i++) { TFSInfo imgurInfo = (TFSInfo)listview_TFS_uploads.SelectedItems[i].Tag; DialogResult result = MessageBox.Show(Language.GetFormattedString(LangKey.delete_question, imgurInfo.Title), Language.GetFormattedString(LangKey.delete_title, imgurInfo.ID), MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(TFSPlugin.Attributes.Name, Language.GetString("tfs", LangKey.communication_wait)); try { TFSUtils.DeleteTfsWorkItem(imgurInfo); } catch (Exception ex) { LOG.Warn("Problem communicating with TFS: ", ex); } finally { backgroundForm.CloseDialog(); } imgurInfo.Dispose(); } } } redraw(); }
public bool Upload(ICaptureDetails captureDetails, Image image) { using (MemoryStream stream = new MemoryStream()) { BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(Attributes.Name, lang.GetString(LangKey.communication_wait)); host.SaveToStream(image, stream, config.UploadFormat, config.UploadJpegQuality); byte[] buffer = stream.GetBuffer(); try { string filename = Path.GetFileName(host.GetFilename(config.UploadFormat, captureDetails)); string contentType = "image/" + config.UploadFormat.ToString(); PicasaInfo picasaInfo = PicasaUtils.UploadToPicasa(buffer, captureDetails.DateTime.ToString(), filename, contentType); if (config.PicasaUploadHistory == null) { config.PicasaUploadHistory = new Dictionary <string, string>(); } if (picasaInfo.ID != null) { LOG.InfoFormat("Storing Picasa upload for id {0}", picasaInfo.ID); config.PicasaUploadHistory.Add(picasaInfo.ID, picasaInfo.ID); config.runtimePicasaHistory.Add(picasaInfo.ID, picasaInfo); } picasaInfo.Image = PicasaUtils.CreateThumbnail(image, 90, 90); // Make sure the configuration is save, so we don't lose the deleteHash IniConfig.Save(); // Make sure the history is loaded, will be done only once PicasaUtils.LoadHistory(); // Show if (config.AfterUploadOpenHistory) { PicasaHistory.ShowHistory(); } if (config.AfterUploadLinkToClipBoard) { Clipboard.SetText(picasaInfo.LinkUrl(config.PictureDisplaySize)); } return(true); } catch (Google.GData.Client.InvalidCredentialsException eLo) { MessageBox.Show(lang.GetString(LangKey.InvalidCredentials)); } catch (Exception e) { MessageBox.Show(lang.GetString(LangKey.upload_failure) + " " + e.ToString()); } finally { backgroundForm.CloseDialog(); } } return(false); }
public static void ShowFDesktop(string[] args) { try { var kernel = new StandardKernel(new CommonModule(), new WinFormsModule()); var hostService = kernel.Get <X86HostService>(); //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); string pipeName = string.Format(X86HostManager.PIPE_NAME_FORMAT, Process.GetCurrentProcess().Id); var form = new BackgroundForm(); hostService.ParentForm = form; using (var host = new ServiceHost(hostService)) { host.AddServiceEndpoint(typeof(IX86HostService), new NetNamedPipeBinding { ReceiveTimeout = TimeSpan.FromHours(24), SendTimeout = TimeSpan.FromHours(24) }, pipeName); host.Open(); Console.Write('k'); form.Show(); } } catch (Exception ex) { Console.Write('k'); Log.FatalException("An error occurred that caused the 32-bit host application to close.", ex); Environment.Exit(1); } }
public WelcomeScreen() { SUI = new UI(); bg_img = new FusionEngine.Texture.Texture2D("data/ui/skin/windowbg1.png", FusionEngine.Texture.LoadMethod.Single, true); BG = (ImageForm) new ImageForm().Set(0, 0, FusionEngine.App.AppInfo.W, FusionEngine.App.AppInfo.H); BG.SetImage(bg_img); MainForm = (WelcomeForm) new WelcomeForm().Set(450, 200, FusionEngine.App.AppInfo.W - 900, 250, "Welcome to Fusion"); BGForm = (BackgroundForm) new BackgroundForm(20).Set(0, 0, FusionEngine.App.AppInfo.W, FusionEngine.App.AppInfo.H); var bgi = new ImageForm().Set(0, 0, FusionEngine.App.AppInfo.W, FusionEngine.App.AppInfo.H, ""); bgi.SetImage(new FusionEngine.Texture.Texture2D("data/ui/bg1.jpg", FusionEngine.Texture.LoadMethod.Single, false)); bgi.Add(BGForm); SUI.Root.Add(bgi); BGForm.Add(MainForm); // SUI.Top = MainForm; MainForm.Create = (user, pass) => { Console.WriteLine("Creating new account. User:"******" Pass:" + pass); }; Com = new FusionEngine.Composition.Composite(); BloomUI = new FusionEngine.Composition.Compositers.BloomUICompositer(); dynamic ui = BloomUI.InputFrame; ui.GUI = SUI; Com.AddCompositer(BloomUI); int t = System.Environment.TickCount + 8000; while (System.Environment.TickCount < t) { } }
/// <summary> /// Do the actual upload to TFS /// </summary> /// <param name="imageData">byte[] with image data</param> /// <returns>TFSResponse</returns> public static TFSInfo UploadToTFS(byte[] imageData, string title, string filename, string contentType) { BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(TFSPlugin.Attributes.Name, Language.GetString("tfs", LangKey.communication_wait)); AddForm addForm = null; try { addForm = new AddForm(); } finally { backgroundForm.CloseDialog(); } addForm.ImageData = imageData; addForm.Title = title; addForm.Filename = filename; addForm.ContentType = contentType; if (addForm.ShowDialog() == DialogResult.OK) { return(addForm.TFSInfo); } else { return(null); } }
private void combobox_workItemType_SelectedIndexChanged(object sender, EventArgs e) { BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(TFSPlugin.Attributes.Name, Language.GetString("tfs", LangKey.communication_wait)); try { this.BindScreenByItemType(); } finally { backgroundForm.CloseDialog(); } }
public static void Run(string[] args) { try { #if DEBUG // Debugger.Launch(); #endif // Initialize Ninject (the DI framework) var kernel = new StandardKernel(new CommonModule(), new WinFormsModule()); // Expect a single argument, the parent process id if (args.Length != 1 || !int.TryParse(args[0], out int procId) || !IsProcessRunning(procId)) { return; } // Set up basic application configuration Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += UnhandledException; TaskScheduler.UnobservedTaskException += UnhandledTaskException; // Set up a form for the worker process // A parent form is needed for some operations, namely 64-bit TWAIN scanning var form = new BackgroundForm(); Invoker.Current = form; // Connect to the main NAPS2 process and listen for assigned work var pipeName = string.Format(WorkerManager.PIPE_NAME_FORMAT, Process.GetCurrentProcess().Id); using (var host = new ServiceHost(typeof(WorkerService))) using (new Timer(CheckParent, procId, 0, PARENT_CHECK_INTERVAL)) { host.Description.Behaviors.Add(new ServiceFactoryBehavior(() => kernel.Get <WorkerService>())); host.AddServiceEndpoint(typeof(IWorkerService), new NetNamedPipeBinding { ReceiveTimeout = TimeSpan.FromHours(24), SendTimeout = TimeSpan.FromHours(24) }, pipeName); host.Open(); // Send a character to stdout to indicate that the process is ready for work Console.Write('k'); Application.Run(form); } } catch (Exception ex) { Console.Write('k'); Log.FatalException("An error occurred that caused the worker application to close.", ex); Environment.Exit(1); } }
void SendToButtonClick(object sender, EventArgs e) { BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(Language.GetString("fogbugz", LangKey.fogbugz), Language.GetString("fogbugz", LangKey.communication_wait)); bool success = false; int caseId = 0; if (ResultsListBox.SelectedIndex == 0) { // TODO: Open new case dialog FogBugz fb = new FogBugz(new Uri(m_cfg.FogBugzServerUrl), m_cfg.FogBugzLoginToken); caseId = fb.CreateNewCase(CaptionTextBox.Text, m_filename, m_captureStream.GetBuffer()); success = true; } else { string item = ResultsListBox.SelectedItem.ToString(); caseId = Convert.ToInt32(item.Substring(0, item.IndexOf(" "))); FogBugz fb = new FogBugz(new Uri(m_cfg.FogBugzServerUrl), m_cfg.FogBugzLoginToken); fb.AttachImageToExistingCase(caseId, CaptionTextBox.Text, m_filename, m_captureStream.GetBuffer()); success = true; } // Set the configuration for next time if (success) { m_cfg.LastCaseId = caseId; try { string caseUrl = string.Concat(m_cfg.FogBugzServerUrl, "?", caseId); if (m_cfg.CopyCaseUrlToClipboardAfterSend) { System.Windows.Forms.Clipboard.SetText(caseUrl); } if (m_cfg.OpenBrowserAfterSend) { Process.Start(caseUrl); } } catch { // Throw away "after-upload" exceptions } } backgroundForm.CloseDialog(); }
/// <summary> /// A form for token /// </summary> /// <returns>bool true if OK was pressed, false if cancel</returns> public bool ShowConfigDialog() { SettingsForm settingsForm; ILanguage lang = Language.GetInstance(); BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(FlickrPlugin.Attributes.Name, lang.GetString(LangKey.communication_wait)); try { settingsForm = new SettingsForm(this); } finally { backgroundForm.CloseDialog(); } settingsForm.AuthToken = this.flickrToken; settingsForm.IsFamily = this.IsFamily; settingsForm.IsPublic = this.IsPublic; settingsForm.IsFriend = this.IsFriend; settingsForm.UploadFormat = this.UploadFormat.ToString(); settingsForm.SafetyLevel = this.SafetyLevel.ToString(); settingsForm.HiddenFromSearch = this.HiddenFromSearch.ToString(); settingsForm.PictureDefaultSize = this.PictureDisplaySize.ToString(); settingsForm.AfterUploadOpenHistory = this.AfterUploadOpenHistory; settingsForm.AfterUploadLinkToClipBoard = this.AfterUploadLinkToClipBoard; DialogResult result = settingsForm.ShowDialog(); if (result == DialogResult.OK) { this.flickrToken = settingsForm.AuthToken; this.IsFamily = settingsForm.IsFamily; this.IsPublic = settingsForm.IsPublic; this.IsFriend = settingsForm.IsFriend; this.SafetyLevel = (FlickrNet.SafetyLevel)Enum.Parse(typeof(FlickrNet.SafetyLevel), settingsForm.SafetyLevel); this.HiddenFromSearch = (FlickrNet.HiddenFromSearch)Enum.Parse(typeof(FlickrNet.HiddenFromSearch), settingsForm.HiddenFromSearch); this.UploadFormat = (OutputFormat)Enum.Parse(typeof(OutputFormat), settingsForm.UploadFormat.ToLower()); this.PictureDisplaySize = (PictureDisplaySize)Enum.Parse(typeof(PictureDisplaySize), settingsForm.PictureDefaultSize); this.AfterUploadOpenHistory = settingsForm.AfterUploadOpenHistory; this.AfterUploadLinkToClipBoard = settingsForm.AfterUploadLinkToClipBoard; IniConfig.Save(); return(true); } return(false); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (var backForm = new BackgroundForm()) { backForm.Show(); using (var login = new LogInDialog()) { if (login.ShowDialog(backForm) != DialogResult.OK) { return; } } } //Application.Run(new Form1()); Application.Run(new MainForm()); }
/// <summary> /// A form for token /// </summary> /// <returns>bool true if OK was pressed, false if cancel</returns> public bool ShowConfigDialog() { SettingsForm settingsForm; BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(TFSPlugin.Attributes.Name, Language.GetString("tfs", LangKey.communication_wait)); try { settingsForm = new SettingsForm(this); } finally { backgroundForm.CloseDialog(); } settingsForm.UploadFormat = this.UploadFormat.ToString(); settingsForm.AfterUploadOpenHistory = this.AfterUploadOpenHistory; settingsForm.AfterUploadLinkToClipBoard = this.AfterUploadLinkToClipBoard; settingsForm.AfterUploadOpenWorkItem = this.AfterUploadOpenWorkItem; settingsForm.ServerUrl = this.TfsServerUrl; settingsForm.DefaultProject = this.TfsDefaultProject; DialogResult result = settingsForm.ShowDialog(); if (result == DialogResult.OK) { this.UploadFormat = (OutputFormat)Enum.Parse(typeof(OutputFormat), settingsForm.UploadFormat.ToLower()); this.AfterUploadOpenHistory = settingsForm.AfterUploadOpenHistory; this.AfterUploadLinkToClipBoard = settingsForm.AfterUploadLinkToClipBoard; this.AfterUploadOpenWorkItem = settingsForm.AfterUploadOpenWorkItem; this.TfsServerUrl = settingsForm.ServerUrl; this.TfsDefaultProject = settingsForm.DefaultProject; IniConfig.Save(); return(true); } return(false); }
/// <summary> /// A form for token /// </summary> /// <returns>bool true if OK was pressed, false if cancel</returns> public bool ShowConfigDialog() { SettingsForm settingsForm; ILanguage lang = Language.GetInstance(); BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(PicasaPlugin.Attributes.Name, lang.GetString(LangKey.communication_wait)); try { settingsForm = new SettingsForm(this); } finally { backgroundForm.CloseDialog(); } settingsForm.UploadFormat = this.UploadFormat.ToString(); settingsForm.AfterUploadOpenHistory = this.AfterUploadOpenHistory; settingsForm.AfterUploadLinkToClipBoard = this.AfterUploadLinkToClipBoard; settingsForm.Username = this.Username; settingsForm.Password = this.Password; settingsForm.PictureDefaultSize = this.PictureDisplaySize.ToString(); DialogResult result = settingsForm.ShowDialog(); if (result == DialogResult.OK) { this.UploadFormat = (OutputFormat)Enum.Parse(typeof(OutputFormat), settingsForm.UploadFormat.ToLower()); this.AfterUploadOpenHistory = settingsForm.AfterUploadOpenHistory; this.AfterUploadLinkToClipBoard = settingsForm.AfterUploadLinkToClipBoard; this.Username = settingsForm.Username; this.Password = settingsForm.Password; this.PictureDisplaySize = (PictureDisplaySize)Enum.Parse(typeof(PictureDisplaySize), settingsForm.PictureDefaultSize); IniConfig.Save(); return(true); } return(false); }
public static void Run(string[] args) { try { // Initialize Ninject (the DI framework) var kernel = new StandardKernel(new CommonModule(), new WinFormsModule()); // Start a pending worker process WorkerManager.Init(); // Set up basic application configuration Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += UnhandledException; TaskScheduler.UnobservedTaskException += UnhandledTaskException; // Set up a form for the server process var form = new BackgroundForm(); Invoker.Current = form; int port = DEFAULT_PORT; foreach (var portArg in args.Where(a => a.StartsWith("/Port:", StringComparison.OrdinalIgnoreCase))) { if (int.TryParse(portArg.Substring(6), out int parsedPort)) { port = parsedPort; } } new Thread(() => ServerDiscovery.ListenForBroadcast(port)) { IsBackground = true }.Start(); // Listen for requests using (var host = new ServiceHost(typeof(ScanService))) { var serverIcon = new ServerNotifyIcon(port, () => form.Close()); host.Opened += (sender, eventArgs) => serverIcon.Show(); host.Description.Behaviors.Add(new ServiceFactoryBehavior(() => kernel.Get <ScanService>())); var binding = new NetTcpBinding { ReceiveTimeout = TimeSpan.FromHours(1), SendTimeout = TimeSpan.FromHours(1), Security = { Mode = SecurityMode.None } }; host.AddServiceEndpoint(typeof(IScanService), binding, $"net.tcp://0.0.0.0:{port}/NAPS2.Server"); host.Open(); try { Application.Run(form); } finally { serverIcon.Hide(); } } } catch (Exception ex) { Log.FatalException("An error occurred that caused the server application to close.", ex); Environment.Exit(1); } }
/// <summary> /// This will be called when the menu item in the Editor is clicked /// </summary> public bool Upload(ICaptureDetails captureDetails, Image image) { if (config.DropboxAccessToken == null) { MessageBox.Show(lang.GetString(LangKey.TokenNotSet), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); return(false); } else { using (MemoryStream stream = new MemoryStream()) { BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(Attributes.Name, lang.GetString(LangKey.communication_wait)); host.SaveToStream(image, stream, config.UploadFormat, config.UploadJpegQuality); byte[] buffer = stream.GetBuffer(); try { string filename = Path.GetFileName(host.GetFilename(config.UploadFormat, captureDetails)); DropboxInfo DropboxInfo = DropboxUtils.UploadToDropbox(buffer, captureDetails.Title, filename); if (config.DropboxUploadHistory == null) { config.DropboxUploadHistory = new Dictionary <string, string>(); } if (DropboxInfo.ID != null) { LOG.InfoFormat("Storing Dropbox upload for id {0}", DropboxInfo.ID); config.DropboxUploadHistory.Add(DropboxInfo.ID, DropboxInfo.ID); config.runtimeDropboxHistory.Add(DropboxInfo.ID, DropboxInfo); } DropboxInfo.Image = DropboxUtils.CreateThumbnail(image, 90, 90); // Make sure the configuration is save, so we don't lose the deleteHash IniConfig.Save(); // Make sure the history is loaded, will be done only once DropboxUtils.LoadHistory(); // Show if (config.AfterUploadOpenHistory) { DropboxHistory.ShowHistory(); } if (config.AfterUploadLinkToClipBoard) { Clipboard.SetText(DropboxInfo.WebUrl); } return(true); } catch (Exception e) { MessageBox.Show(lang.GetString(LangKey.upload_failure) + " " + e.ToString()); return(false); } finally { backgroundForm.CloseDialog(); } } } }
/// <summary> /// Here the logic for capturing the IE Content is located /// </summary> /// <param name="capture">ICapture where the capture needs to be stored</param> /// <param name="windowToCapture">window to use</param> /// <returns>ICapture with the content (if any)</returns> public static ICapture CaptureIE(ICapture capture, WindowDetails windowToCapture) { if (windowToCapture == null) { windowToCapture = WindowDetails.GetActiveWindow(); } // Show backgroundform after retrieving the active window.. BackgroundForm backgroundForm = new BackgroundForm(Language.GetString(LangKey.contextmenu_captureie), Language.GetString(LangKey.wait_ie_capture)); backgroundForm.Show(); //BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(language.GetString(LangKey.contextmenu_captureie), language.GetString(LangKey.wait_ie_capture)); try { //Get IHTMLDocument2 for the current active window DocumentContainer documentContainer = CreateDocumentContainer(windowToCapture); // Nothing found if (documentContainer == null) { LOG.Debug("Nothing to capture found"); return(null); } try { LOG.DebugFormat("Window class {0}", documentContainer.ContentWindow.ClassName); LOG.DebugFormat("Window location {0}", documentContainer.ContentWindow.Location); } catch (Exception ex) { LOG.Warn("Error while logging information.", ex); } // bitmap to return Bitmap returnBitmap = null; Size pageSize = Size.Empty; try { pageSize = PrepareCapture(documentContainer, capture); returnBitmap = capturePage(documentContainer, capture, pageSize); } catch (Exception captureException) { LOG.Error("Exception found, ignoring and returning nothing! Error was: ", captureException); } // TODO: Enable when the elements are usable again. // Capture the element on the page //try { // if (configuration.IEFieldCapture && capture.CaptureDetails.HasDestination("Editor")) { // // clear the current elements, as they are for the window itself // capture.Elements.Clear(); // CaptureElement documentCaptureElement = documentContainer.CreateCaptureElements(pageSize); // foreach(DocumentContainer frameDocument in documentContainer.Frames) { // try { // CaptureElement frameCaptureElement = frameDocument.CreateCaptureElements(Size.Empty); // if (frameCaptureElement != null) { // documentCaptureElement.Children.Add(frameCaptureElement); // } // } catch (Exception ex) { // LOG.Warn("An error occurred while creating the capture elements: ", ex); // } // } // capture.AddElement(documentCaptureElement); // // Offset the elements, as they are "back offseted" later... // Point windowLocation = documentContainer.ContentWindow.WindowRectangle.Location; // capture.MoveElements(-(capture.ScreenBounds.Location.X-windowLocation.X), -(capture.ScreenBounds.Location.Y-windowLocation.Y)); // } //} catch (Exception elementsException) { // LOG.Warn("An error occurred while creating the capture elements: ", elementsException); //} if (returnBitmap == null) { return(null); } // Store the bitmap for further processing capture.Image = returnBitmap; try { // Store the location of the window capture.Location = documentContainer.ContentWindow.Location; // The URL is available unter "document2.url" and can be used to enhance the meta-data etc. capture.CaptureDetails.AddMetaData("url", documentContainer.Url); // Store the title of the page if (documentContainer.Name != null) { capture.CaptureDetails.Title = documentContainer.Name; } else { capture.CaptureDetails.Title = windowToCapture.Text; } } catch (Exception ex) { LOG.Warn("Problems getting some attributes...", ex); } // Store the URL of the page if (documentContainer.Url != null) { try { Uri uri = new Uri(documentContainer.Url); capture.CaptureDetails.AddMetaData("URL", uri.OriginalString); // As the URL can hardly be used in a filename, the following can be used if (!string.IsNullOrEmpty(uri.Scheme)) { capture.CaptureDetails.AddMetaData("URL_SCHEME", uri.Scheme); } if (!string.IsNullOrEmpty(uri.DnsSafeHost)) { capture.CaptureDetails.AddMetaData("URL_HOSTNAME", uri.DnsSafeHost); } if (!string.IsNullOrEmpty(uri.AbsolutePath)) { capture.CaptureDetails.AddMetaData("URL_PATH", uri.AbsolutePath); } if (!string.IsNullOrEmpty(uri.Query)) { capture.CaptureDetails.AddMetaData("URL_QUERY", uri.Query); } if (!string.IsNullOrEmpty(uri.UserInfo)) { capture.CaptureDetails.AddMetaData("URL_USER", uri.UserInfo); } capture.CaptureDetails.AddMetaData("URL_PORT", uri.Port.ToString()); } catch (Exception e) { LOG.Warn("Exception when trying to use url in metadata " + documentContainer.Url, e); } } try { // Only move the mouse to correct for the capture offset capture.MoveMouseLocation(-documentContainer.ViewportRectangle.X, -documentContainer.ViewportRectangle.Y); // Used to be: capture.MoveMouseLocation(-(capture.Location.X + documentContainer.CaptureOffset.X), -(capture.Location.Y + documentContainer.CaptureOffset.Y)); } catch (Exception ex) { LOG.Warn("Error while correcting the mouse offset.", ex); } } finally { // Always close the background form backgroundForm.CloseDialog(); } return(capture); }
private void button1_Click(object sender, EventArgs e) { var workerw = GetHandle(); string gifPath = ""; //Select a gif file to be placed in the picture box. using (OpenFileDialog openFileDialog = new OpenFileDialog { Filter = "Gif files (*.gif)|*.gif", Title = "Open gif file", AutoUpgradeEnabled = false }) { if (openFileDialog.ShowDialog() != DialogResult.OK) { return; } try { //Set variables to match the data returned by the selected image gifPath = openFileDialog.FileName; //Set the value in the picturebox as a preview of the selected image pictureBox1.ImageLocation = gifPath; pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return; } } // Create a new background form var form = new BackgroundForm(); //Fetch the selected monitor int monitorId = int.Parse(numericUpDown1.Value.ToString()); //Attempt to remove previously allocated items from that monitor if (Forms.TryGetValue(monitorId, out var currentForm)) { currentForm.Form.Close(); Forms.Remove(monitorId); } Forms.Add(monitorId, form); // Set the background forum to be borderless form.Form.FormBorderStyle = FormBorderStyle.None; form.Form.Text = "PassiveWallpaper"; Screen selectedScreen = Screen.AllScreens[monitorId]; //On the loading of the background form set the new properties form.Form.Load += (s, e2) => { //Ensure the form takes up the entire screen size of the selected monitor form.Form.Width = selectedScreen.Bounds.Width; form.Form.Height = selectedScreen.Bounds.Height; form.Form.Left = selectedScreen.Bounds.X; form.Form.Top = selectedScreen.Bounds.Y; //Create a new picturebox that fills the form and set it's image contents PictureBox pic = new PictureBox { Width = form.Form.Width, Height = form.Form.Height, Left = 0, Top = 0, Name = "PictureBox", ImageLocation = gifPath, SizeMode = PictureBoxSizeMode.StretchImage }; if (transparent.Checked) { //Set the image to be transparent backgrounded and set it's background image to be the current desktop background. pic.BackColor = Color.Transparent; pic.BackgroundImage = new Bitmap(GetCurrentWallpaperPath()); } else { pic.BackColor = Color.White; pic.BackgroundImage = null; } //Add the picturebox to the form form.Form.Controls.Add(pic); //Ensure the parent of the new form is the WorkerW process that was spawned between the desktop wallpaper and icons Natives.SetParent(form.Form.Handle, workerw); }; //Ensure that the closing event of the form is set in order to re-set the current desktop wallpaper and 'refresh' it, removing any artifacts form.Form.Closing += (s2, a2) => SetImage(); //Finally display the new form to the user. form.Form.Show(); }
private void InternalScan(TwainImpl twainImpl, IWin32Window dialogParent, ScanDevice scanDevice, ScanProfile scanProfile, ScanParams scanParams, CancellationToken cancelToken, ScannedImageSource.Concrete source, Action <ScannedImage, ScanParams, string> runBackgroundOcr) { if (dialogParent == null) { dialogParent = new BackgroundForm(); } if (twainImpl == TwainImpl.Legacy) { Legacy.TwainApi.Scan(scanProfile, scanDevice, dialogParent, formFactory, source); return; } PlatformInfo.Current.PreferNewDSM = twainImpl != TwainImpl.OldDsm; var session = new TwainSession(TwainAppId); var twainForm = Invoker.Current.InvokeGet(() => scanParams.NoUI ? null : formFactory.Create <FTwainGui>()); Exception error = null; bool cancel = false; DataSource ds = null; var waitHandle = new AutoResetEvent(false); int pageNumber = 0; session.TransferReady += (sender, eventArgs) => { Debug.WriteLine("NAPS2.TW - TransferReady"); if (cancel) { eventArgs.CancelAll = true; } }; session.DataTransferred += (sender, eventArgs) => { try { Debug.WriteLine("NAPS2.TW - DataTransferred"); pageNumber++; using (var output = twainImpl == TwainImpl.MemXfer ? GetBitmapFromMemXFer(eventArgs.MemoryData, eventArgs.ImageInfo) : Image.FromStream(eventArgs.GetNativeImageStream())) { using (var result = scannedImageHelper.PostProcessStep1(output, scanProfile)) { if (blankDetector.ExcludePage(result, scanProfile)) { return; } var bitDepth = output.PixelFormat == PixelFormat.Format1bppIndexed ? ScanBitDepth.BlackWhite : ScanBitDepth.C24Bit; var image = new ScannedImage(result, bitDepth, scanProfile.MaxQuality, scanProfile.Quality); if (scanParams.DetectPatchCodes) { foreach (var patchCodeInfo in eventArgs.GetExtImageInfo(ExtendedImageInfo.PatchCode)) { if (patchCodeInfo.ReturnCode == ReturnCode.Success) { image.PatchCode = GetPatchCode(patchCodeInfo); } } } scannedImageHelper.PostProcessStep2(image, result, scanProfile, scanParams, pageNumber); string tempPath = scannedImageHelper.SaveForBackgroundOcr(result, scanParams); runBackgroundOcr(image, scanParams, tempPath); source.Put(image); } } } catch (Exception ex) { Debug.WriteLine("NAPS2.TW - DataTransferred - Error"); error = ex; cancel = true; StopTwain(); } }; session.TransferError += (sender, eventArgs) => { Debug.WriteLine("NAPS2.TW - TransferError"); if (eventArgs.Exception != null) { error = eventArgs.Exception; } else if (eventArgs.SourceStatus != null) { Log.Error("TWAIN Transfer Error. Return code = {0}; condition code = {1}; data = {2}.", eventArgs.ReturnCode, eventArgs.SourceStatus.ConditionCode, eventArgs.SourceStatus.Data); } else { Log.Error("TWAIN Transfer Error. Return code = {0}.", eventArgs.ReturnCode); } cancel = true; StopTwain(); }; session.SourceDisabled += (sender, eventArgs) => { Debug.WriteLine("NAPS2.TW - SourceDisabled"); StopTwain(); }; void StopTwain() { waitHandle.Set(); if (!scanParams.NoUI) { Invoker.Current.Invoke(() => twainForm.Close()); } } void InitTwain() { try { var windowHandle = (Invoker.Current as Form)?.Handle; ReturnCode rc = windowHandle != null?session.Open(new WindowsFormsMessageLoopHook(windowHandle.Value)) : session.Open(); if (rc != ReturnCode.Success) { Debug.WriteLine("NAPS2.TW - Could not open session - {0}", rc); StopTwain(); return; } ds = session.FirstOrDefault(x => x.Name == scanDevice.ID); if (ds == null) { Debug.WriteLine("NAPS2.TW - Could not find DS - DS count = {0}", session.Count()); throw new DeviceNotFoundException(); } rc = ds.Open(); if (rc != ReturnCode.Success) { Debug.WriteLine("NAPS2.TW - Could not open DS - {0}", rc); StopTwain(); return; } ConfigureDS(ds, scanProfile, scanParams); var ui = scanProfile.UseNativeUI ? SourceEnableMode.ShowUI : SourceEnableMode.NoUI; Debug.WriteLine("NAPS2.TW - Enabling DS"); rc = scanParams.NoUI ? ds.Enable(ui, true, windowHandle ?? IntPtr.Zero) : ds.Enable(ui, true, twainForm.Handle); Debug.WriteLine("NAPS2.TW - Enable finished"); if (rc != ReturnCode.Success) { Debug.WriteLine("NAPS2.TW - Enable failed - {0}, rc"); StopTwain(); } else { cancelToken.Register(() => { Debug.WriteLine("NAPS2.TW - User Cancel"); cancel = true; session.ForceStepDown(5); }); } } catch (Exception ex) { Debug.WriteLine("NAPS2.TW - Error"); error = ex; StopTwain(); } } if (!scanParams.NoUI) { twainForm.Shown += (sender, eventArgs) => { InitTwain(); }; twainForm.Closed += (sender, args) => waitHandle.Set(); } if (scanParams.NoUI) { Debug.WriteLine("NAPS2.TW - Init with no form"); Invoker.Current.Invoke(InitTwain); } else if (!scanParams.Modal) { Debug.WriteLine("NAPS2.TW - Init with non-modal form"); Invoker.Current.Invoke(() => twainForm.Show(dialogParent)); } else { Debug.WriteLine("NAPS2.TW - Init with modal form"); Invoker.Current.Invoke(() => twainForm.ShowDialog(dialogParent)); } waitHandle.WaitOne(); Debug.WriteLine("NAPS2.TW - Operation complete"); if (ds != null && session.IsSourceOpen) { Debug.WriteLine("NAPS2.TW - Closing DS"); ds.Close(); } if (session.IsDsmOpen) { Debug.WriteLine("NAPS2.TW - Closing session"); session.Close(); } if (error != null) { Debug.WriteLine("NAPS2.TW - Throwing error - {0}", error); if (error is ScanDriverException) { throw error; } throw new ScanDriverUnknownException(error); } }
/// <summary> /// Here the logic for capturing the IE Content is located /// </summary> /// <param name="capture">ICapture where the capture needs to be stored</param> /// <returns>ICapture with the content (if any)</returns> public static ICapture CaptureIE(ICapture capture) { WindowDetails activeWindow = WindowDetails.GetActiveWindow(); // Show backgroundform after retrieving the active window.. BackgroundForm backgroundForm = new BackgroundForm(language.GetString(LangKey.contextmenu_captureie), language.GetString(LangKey.wait_ie_capture)); backgroundForm.Show(); //BackgroundForm backgroundForm = BackgroundForm.ShowAndWait(language.GetString(LangKey.contextmenu_captureie), language.GetString(LangKey.wait_ie_capture)); try { //Get IHTMLDocument2 for the current active window DocumentContainer documentContainer = GetDocument(activeWindow); // Nothing found if (documentContainer == null) { LOG.Debug("Nothing to capture found"); return(null); } LOG.DebugFormat("Window class {0}", documentContainer.ContentWindow.ClassName); LOG.DebugFormat("Window location {0}", documentContainer.ContentWindow.Location); // The URL is available unter "document2.url" and can be used to enhance the meta-data etc. capture.CaptureDetails.AddMetaData("url", documentContainer.Url); // bitmap to return Bitmap returnBitmap = null; try { returnBitmap = capturePage(documentContainer, capture); } catch (Exception e) { LOG.Error("Exception found, ignoring and returning nothing! Error was: ", e); } if (returnBitmap == null) { return(null); } // Store the bitmap for further processing capture.Image = returnBitmap; // Store the location of the window capture.Location = documentContainer.ContentWindow.Location; // Store the title of the Page if (documentContainer.Name != null) { capture.CaptureDetails.Title = documentContainer.Name; } else { capture.CaptureDetails.Title = activeWindow.Text; } // Only move the mouse to correct for the capture offset capture.MoveMouseLocation(-documentContainer.ViewportRectangle.X, -documentContainer.ViewportRectangle.Y); // Used to be: capture.MoveMouseLocation(-(capture.Location.X + documentContainer.CaptureOffset.X), -(capture.Location.Y + documentContainer.CaptureOffset.Y)); } finally { // Always close the background form backgroundForm.CloseDialog(); } return(capture); }