Beispiel #1
0
 private void btnFullscreen_Click(object sender, EventArgs e)
 {
     UpdateRegion(CaptureHelpers.GetScreenBounds());
 }
Beispiel #2
0
        public void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, bool skipRegionSelection = false)
        {
            string debugText;

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                debugText = string.Format("Starting FFmpeg recording. Video encoder: \"{0}\", Audio encoder: \"{1}\", FPS: {2}",
                                          taskSettings.CaptureSettings.FFmpegOptions.VideoCodec.GetDescription(), taskSettings.CaptureSettings.FFmpegOptions.AudioCodec.GetDescription(),
                                          taskSettings.CaptureSettings.ScreenRecordFPS);
            }
            else
            {
                debugText = string.Format("Starting Animated GIF recording. GIF encoding: \"{0}\", FPS: {1}",
                                          taskSettings.CaptureSettings.GIFEncoding.GetDescription(), taskSettings.CaptureSettings.GIFFPS);
            }

            DebugHelper.WriteLine(debugText);

            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_There_is_no_valid_CLI_video_encoder_selected_,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_CLI_video_encoder_file_does_not_exist__ +
                                    Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (outputType == ScreenRecordOutput.GIF && taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.FFmpeg)
            {
                outputType = ScreenRecordOutput.FFmpeg;
                taskSettings.CaptureSettings.FFmpegOptions.VideoCodec = FFmpegVideoCodec.gif;
            }

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                if (!File.Exists(taskSettings.CaptureSettings.FFmpegOptions.CLIPath))
                {
                    string ffmpegText = string.IsNullOrEmpty(taskSettings.CaptureSettings.FFmpegOptions.CLIPath) ? "ffmpeg.exe" : taskSettings.CaptureSettings.FFmpegOptions.CLIPath;

                    if (MessageBox.Show(string.Format(Resources.ScreenRecordForm_StartRecording_does_not_exist, ffmpegText),
                                        "ShareX - " + Resources.ScreenRecordForm_StartRecording_Missing + " ffmpeg.exe", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        if (FFmpegDownloader.DownloadFFmpeg(false, DownloaderForm_InstallRequested) == DialogResult.OK)
                        {
                            Program.DefaultTaskSettings.CaptureSettings.FFmpegOptions.CLIPath = taskSettings.TaskSettingsReference.CaptureSettings.FFmpegOptions.CLIPath =
                                taskSettings.CaptureSettings.FFmpegOptions.CLIPath            = Path.Combine(Program.ToolsFolder, "ffmpeg.exe");
                        }
                    }
                    else
                    {
                        return;
                    }
                }

                if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                    "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            Rectangle captureRectangle;

            if (skipRegionSelection)
            {
                captureRectangle = Program.Settings.ScreenRecordRegion;
            }
            else
            {
                TaskHelpers.SelectRegion(out captureRectangle, taskSettings);
                captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);
            }

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;
            Screenshot.CaptureCursor = taskSettings.CaptureSettings.ShowCursor;

            string trayText = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Waiting___;

            TrayIcon.Text    = trayText.Truncate(63);
            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            TrayIcon.Visible = true;

            string path = "";

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            regionForm = ScreenRegionForm.Show(captureRectangle, StopRecording, duration);
            regionForm.RecordResetEvent = new ManualResetEvent(false);

            TaskEx.Run(() =>
            {
                try
                {
                    if (outputType == ScreenRecordOutput.FFmpeg)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension));
                    }
                    else
                    {
                        path = Program.ScreenRecorderCacheFilePath;
                    }

                    ScreencastOptions options = new ScreencastOptions()
                    {
                        FFmpeg          = taskSettings.CaptureSettings.FFmpegOptions,
                        ScreenRecordFPS = taskSettings.CaptureSettings.ScreenRecordFPS,
                        GIFFPS          = taskSettings.CaptureSettings.GIFFPS,
                        Duration        = duration,
                        OutputPath      = path,
                        CaptureArea     = captureRectangle,
                        DrawCursor      = taskSettings.CaptureSettings.ShowCursor
                    };

                    screenRecorder = new ScreenRecorder(outputType, options, captureRectangle);

                    if (regionForm != null && regionForm.RecordResetEvent != null)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_start_recording_;
                        TrayIcon.Text = trayText.Truncate(63);

                        if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                        {
                            int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                            if (delay > 0)
                            {
                                regionForm.RecordResetEvent.WaitOne(delay);
                            }
                        }
                        else
                        {
                            regionForm.RecordResetEvent.WaitOne();
                        }

                        if (regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }

                    if (!abortRequested)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_stop_recording_;
                        TrayIcon.Text = trayText.Truncate(63);
                        TrayIcon.Icon = Resources.control_record.ToIcon();

                        if (regionForm != null)
                        {
                            regionForm.InvokeSafe(() => regionForm.StartTimer());
                        }

                        screenRecorder.StartRecording();

                        if (regionForm != null && regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }
                finally
                {
                    if (regionForm != null)
                    {
                        if (regionForm.RecordResetEvent != null)
                        {
                            regionForm.RecordResetEvent.Dispose();
                        }

                        regionForm.InvokeSafe(() => regionForm.Close());
                        regionForm = null;
                    }
                }

                try
                {
                    if (!abortRequested && screenRecorder != null)
                    {
                        TrayIcon.Text = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Encoding___;
                        TrayIcon.Icon = Resources.camcorder_pencil.ToIcon();

                        if (outputType == ScreenRecordOutput.GIF)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.EncodingProgressChanged += progress => TrayIcon.Text = string.Format("ShareX - {0} ({1}%)", Resources.ScreenRecordForm_StartRecording_Encoding___, progress);
                            GIFQuality gifQuality = taskSettings.CaptureSettings.GIFEncoding == ScreenRecordGIFEncoding.OctreeQuantizer ? GIFQuality.Bit8 : GIFQuality.Default;
                            screenRecorder.SaveAsGIF(path, gifQuality);
                        }
                        else if (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.FFmpegEncodeAsGIF(path);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder  = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            string sourceFilePath = path;
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (screenRecorder != null)
                    {
                        if ((outputType == ScreenRecordOutput.GIF || taskSettings.CaptureSettings.RunScreencastCLI ||
                             (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)) &&
                            !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;

                        if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                }
            },
                       () =>
            {
                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings))
                {
                    UploadTask task = UploadTask.CreateFileJobTask(path, taskSettings);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
Beispiel #3
0
 private void UpdateColor(int x, int y)
 {
     UpdateColor(x, y, CaptureHelpers.GetPixelColor(x, y));
 }
        public static Image CaptureWindowTransparent(IntPtr handle)
        {
            if (handle.ToInt32() > 0)
            {
                Rectangle rect = CaptureHelpers.GetWindowRectangle(handle);

                if (CaptureShadow && !NativeMethods.IsZoomed(handle) && NativeMethods.IsDWMEnabled())
                {
                    rect.Inflate(ShadowOffset, ShadowOffset);
                    rect.Intersect(CaptureHelpers.GetScreenBounds());
                }

                Bitmap     whiteBackground = null, blackBackground = null, whiteBackground2 = null;
                CursorData cursor = null;
                bool       isTransparent = false, isTaskbarHide = false;

                try
                {
                    if (AutoHideTaskbar)
                    {
                        isTaskbarHide = NativeMethods.SetTaskbarVisibilityIfIntersect(false, rect);
                    }

                    if (CaptureCursor)
                    {
                        try
                        {
                            cursor = new CursorData();
                        }
                        catch (Exception e)
                        {
                            DebugHelper.WriteException(e, "Cursor capture failed.");
                        }
                    }

                    using (Form form = new Form())
                    {
                        form.BackColor       = Color.White;
                        form.FormBorderStyle = FormBorderStyle.None;
                        form.ShowInTaskbar   = false;

                        NativeMethods.ShowWindow(form.Handle, (int)WindowShowStyle.ShowNormalNoActivate);

                        if (!NativeMethods.SetWindowPos(form.Handle, handle, rect.X, rect.Y, rect.Width, rect.Height, NativeMethods.SWP_NOACTIVATE))
                        {
                            form.Close();
                            DebugHelper.WriteLine("Transparent capture failed. Reason: SetWindowPos fail.");
                            return(CaptureWindow(handle));
                        }

                        Thread.Sleep(10);
                        Application.DoEvents();

                        whiteBackground = (Bitmap)CaptureRectangleNative(rect);

                        form.BackColor = Color.Black;
                        Application.DoEvents();

                        blackBackground = (Bitmap)CaptureRectangleNative(rect);

                        form.BackColor = Color.White;
                        Application.DoEvents();

                        whiteBackground2 = (Bitmap)CaptureRectangleNative(rect);

                        form.Close();
                    }

                    Bitmap transparentImage;

                    if (ImageHelpers.IsImagesEqual(whiteBackground, whiteBackground2))
                    {
                        transparentImage = CreateTransparentImage(whiteBackground, blackBackground);
                        isTransparent    = true;
                    }
                    else
                    {
                        DebugHelper.WriteLine("Transparent capture failed. Reason: Images not equal.");
                        transparentImage = whiteBackground2;
                    }

                    if (cursor != null && cursor.IsVisible)
                    {
                        Point cursorOffset = CaptureHelpers.ScreenToClient(rect.Location);
                        cursor.DrawCursorToImage(transparentImage, cursorOffset);
                    }

                    if (isTransparent)
                    {
                        transparentImage = TrimTransparent(transparentImage);

                        if (!CaptureShadow)
                        {
                            TrimShadow(transparentImage);
                        }
                    }

                    return(transparentImage);
                }
                finally
                {
                    if (isTaskbarHide)
                    {
                        NativeMethods.SetTaskbarVisibility(true);
                    }

                    if (whiteBackground != null)
                    {
                        whiteBackground.Dispose();
                    }
                    if (blackBackground != null)
                    {
                        blackBackground.Dispose();
                    }
                    if (isTransparent && whiteBackground2 != null)
                    {
                        whiteBackground2.Dispose();
                    }
                    if (cursor != null)
                    {
                        cursor.Dispose();
                    }
                }
            }

            return(null);
        }
        private static void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, ScreenRecordStartMethod startMethod = ScreenRecordStartMethod.Region)
        {
            if (outputType == ScreenRecordOutput.GIF)
            {
                taskSettings.CaptureSettings.FFmpegOptions.VideoCodec = FFmpegVideoCodec.gif;
            }

            if (taskSettings.CaptureSettings.FFmpegOptions.IsAnimatedImage)
            {
                taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding = true;
            }

            int fps;

            if (taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)
            {
                fps = taskSettings.CaptureSettings.GIFFPS;
            }
            else
            {
                fps = taskSettings.CaptureSettings.ScreenRecordFPS;
            }

            DebugHelper.WriteLine("Starting screen recording. Video encoder: \"{0}\", Audio encoder: \"{1}\", FPS: {2}",
                                  taskSettings.CaptureSettings.FFmpegOptions.VideoCodec.GetDescription(), taskSettings.CaptureSettings.FFmpegOptions.AudioCodec.GetDescription(), fps);

            if (!TaskHelpers.CheckFFmpeg(taskSettings))
            {
                return;
            }

            if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
            {
                MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Rectangle captureRectangle = Rectangle.Empty;

            switch (startMethod)
            {
            case ScreenRecordStartMethod.Region:
                RegionCaptureTasks.GetRectangleRegion(out captureRectangle, taskSettings.CaptureSettings.SurfaceOptions);
                break;

            case ScreenRecordStartMethod.ActiveWindow:
                if (taskSettings.CaptureSettings.CaptureClientArea)
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowClientRectangle();
                }
                else
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowRectangle();
                }
                break;

            case ScreenRecordStartMethod.CustomRegion:
                captureRectangle = taskSettings.CaptureSettings.CaptureCustomRegion;
                break;

            case ScreenRecordStartMethod.LastRegion:
                captureRectangle = Program.Settings.ScreenRecordRegion;
                break;
            }

            Rectangle screenRectangle = CaptureHelpers.GetScreenBounds();

            captureRectangle = Rectangle.Intersect(captureRectangle, screenRectangle);

            if (taskSettings.CaptureSettings.FFmpegOptions.IsEvenSizeRequired)
            {
                captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);
            }

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;

            string path           = "";
            bool   abortRequested = false;

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            recordForm = new ScreenRecordForm(captureRectangle, taskSettings, startMethod == ScreenRecordStartMethod.Region, duration);
            recordForm.StopRequested += StopRecording;
            recordForm.Show();

            Task.Run(() =>
            {
                try
                {
                    string extension;
                    if (taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding)
                    {
                        extension = "mp4";
                    }
                    else
                    {
                        extension = taskSettings.CaptureSettings.FFmpegOptions.Extension;
                    }
                    string filename = TaskHelpers.GetFilename(taskSettings, extension);
                    path            = TaskHelpers.HandleExistsFile(taskSettings.CaptureFolder, filename, taskSettings);

                    if (string.IsNullOrEmpty(path))
                    {
                        abortRequested = true;
                    }

                    if (!abortRequested)
                    {
                        recordForm.ChangeState(ScreenRecordState.BeforeStart);

                        if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                        {
                            int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                            if (delay > 0)
                            {
                                recordForm.InvokeSafe(() => recordForm.StartCountdown(delay));

                                recordForm.RecordResetEvent.WaitOne(delay);
                            }
                        }
                        else
                        {
                            recordForm.RecordResetEvent.WaitOne();
                        }

                        if (recordForm.IsAbortRequested)
                        {
                            abortRequested = true;
                        }

                        if (!abortRequested)
                        {
                            ScreencastOptions options = new ScreencastOptions()
                            {
                                IsRecording = true,
                                IsLossless  = taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding,
                                FFmpeg      = taskSettings.CaptureSettings.FFmpegOptions,
                                FPS         = fps,
                                Duration    = duration,
                                OutputPath  = path,
                                CaptureArea = captureRectangle,
                                DrawCursor  = taskSettings.CaptureSettings.ScreenRecordShowCursor
                            };

                            Screenshot screenshot    = TaskHelpers.GetScreenshot(taskSettings);
                            screenshot.CaptureCursor = taskSettings.CaptureSettings.ScreenRecordShowCursor;

                            screenRecorder = new ScreenRecorder(ScreenRecordOutput.FFmpeg, options, screenshot, captureRectangle);
                            screenRecorder.RecordingStarted += () => recordForm.ChangeState(ScreenRecordState.AfterRecordingStart);
                            recordForm.ChangeState(ScreenRecordState.AfterStart);
                            screenRecorder.StartRecording();

                            if (recordForm.IsAbortRequested)
                            {
                                abortRequested = true;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }

                if (taskSettings.CaptureSettings.ScreenRecordTwoPassEncoding && !abortRequested && screenRecorder != null && File.Exists(path))
                {
                    recordForm.ChangeState(ScreenRecordState.Encoding);

                    path = ProcessTwoPassEncoding(path, taskSettings);
                }

                if (recordForm != null)
                {
                    recordForm.InvokeSafe(() =>
                    {
                        recordForm.Close();
                        recordForm.Dispose();
                        recordForm = null;
                    });
                }

                if (screenRecorder != null)
                {
                    screenRecorder.Dispose();
                    screenRecorder = null;

                    if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
            }).ContinueInCurrentContext(() =>
            {
                string customFileName;

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings, out customFileName, null, path))
                {
                    if (!string.IsNullOrEmpty(customFileName))
                    {
                        string currentFilename = Path.GetFileNameWithoutExtension(path);
                        string ext             = Path.GetExtension(path);

                        if (!currentFilename.Equals(customFileName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            path = Helpers.RenameFile(path, customFileName + ext);
                        }
                    }

                    WorkerTask task = WorkerTask.CreateFileJobTask(path, taskSettings, customFileName);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
Beispiel #6
0
        private void DrawMagnifier(Graphics g)
        {
            Point     mousePos = InputManager.MousePosition0Based;
            Rectangle currentScreenRect0Based = CaptureHelpers.ScreenToClient(Screen.FromPoint(InputManager.MousePosition).Bounds);
            int       offsetX = 10, offsetY = 10, infoTextOffset = 0, infoTextPadding = 3;
            Rectangle infoTextRect = Rectangle.Empty;
            string    infoText = string.Empty;

            if (Config.ShowInfo)
            {
                infoTextOffset = 10;

                CurrentPosition = InputManager.MousePosition;

                infoText = GetInfoText();
                Size textSize = g.MeasureString(infoText, infoFont).ToSize();
                infoTextRect.Size = new Size(textSize.Width + infoTextPadding * 2, textSize.Height + infoTextPadding * 2);
            }

            using (Bitmap magnifier = Magnifier(SurfaceImage, mousePos, Config.MagnifierPixelCount, Config.MagnifierPixelCount, Config.MagnifierPixelSize))
            {
                int x = mousePos.X + offsetX;

                if (x + magnifier.Width > currentScreenRect0Based.Right)
                {
                    x = mousePos.X - offsetX - magnifier.Width;
                }

                int y = mousePos.Y + offsetY;

                if (y + magnifier.Height + infoTextOffset + infoTextRect.Height > currentScreenRect0Based.Bottom)
                {
                    y = mousePos.Y - offsetY - magnifier.Height - infoTextOffset - infoTextRect.Height;
                }

                if (Config.ShowInfo)
                {
                    infoTextRect.Location = new Point(x + (magnifier.Width / 2) - (infoTextRect.Width / 2), y + magnifier.Height + infoTextOffset);
                    DrawInfoText(g, infoText, infoTextRect, infoTextPadding);
                }

                g.SetHighQuality();

                using (TextureBrush brush = new TextureBrush(magnifier))
                {
                    brush.TranslateTransform(x, y);

                    if (Config.UseSquareMagnifier)
                    {
                        g.FillRectangle(brush, x, y, magnifier.Width, magnifier.Height);
                        g.DrawRectangleProper(Pens.White, x - 1, y - 1, magnifier.Width + 2, magnifier.Height + 2);
                        g.DrawRectangleProper(Pens.Black, x, y, magnifier.Width, magnifier.Height);
                    }
                    else
                    {
                        g.FillEllipse(brush, x, y, magnifier.Width, magnifier.Height);
                        g.DrawEllipse(Pens.White, x - 1, y - 1, magnifier.Width + 2, magnifier.Height + 2);
                        g.DrawEllipse(Pens.Black, x, y, magnifier.Width, magnifier.Height);
                    }
                }
            }
        }
        public virtual void OnNodeUpdate()
        {
            for (int i = 0; i < 8; i++)
            {
                ResizeNode node = Manager.ResizeNodes[i];

                if (node.IsDragging)
                {
                    Manager.IsResizing = true;

                    if (!InputManager.IsBeforeMouseDown(MouseButtons.Left))
                    {
                        tempNodePos  = node.Position;
                        tempStartPos = Rectangle.Location;
                        tempEndPos   = new Point(Rectangle.X + Rectangle.Width - 1, Rectangle.Y + Rectangle.Height - 1);
                    }

                    Point pos      = InputManager.MousePosition0Based;
                    Point startPos = tempStartPos;
                    Point endPos   = tempEndPos;

                    NodePosition nodePosition = (NodePosition)i;

                    int x = pos.X - tempNodePos.X;

                    switch (nodePosition)
                    {
                    case NodePosition.TopLeft:
                    case NodePosition.Left:
                    case NodePosition.BottomLeft:
                        startPos.X += x;
                        break;

                    case NodePosition.TopRight:
                    case NodePosition.Right:
                    case NodePosition.BottomRight:
                        endPos.X += x;
                        break;
                    }

                    int y = pos.Y - tempNodePos.Y;

                    switch (nodePosition)
                    {
                    case NodePosition.TopLeft:
                    case NodePosition.Top:
                    case NodePosition.TopRight:
                        startPos.Y += y;
                        break;

                    case NodePosition.BottomLeft:
                    case NodePosition.Bottom:
                    case NodePosition.BottomRight:
                        endPos.Y += y;
                        break;
                    }

                    Rectangle = CaptureHelpers.CreateRectangle(startPos, endPos);
                }
            }
        }
Beispiel #8
0
        private void DrawFPS(Graphics g, int offset)
        {
            Rectangle screenBounds = CaptureHelpers.GetActiveScreenBounds0Based();

            g.DrawTextWithShadow(FPS.ToString(), screenBounds.Location.Add(offset), infoFontBig, Brushes.White, Brushes.Black, new Point(0, 1));
        }
Beispiel #9
0
        private void DrawCursorGraphics(Graphics g)
        {
            Point     mousePos = InputManager.MousePosition0Based;
            Rectangle currentScreenRect0Based = CaptureHelpers.GetActiveScreenBounds0Based();
            int       cursorOffsetX = 10, cursorOffsetY = 10, itemGap = 10, itemCount = 0;
            Size      totalSize = Size.Empty;

            int    magnifierPosition = 0;
            Bitmap magnifier    = null;

            if (Config.ShowMagnifier)
            {
                if (itemCount > 0)
                {
                    totalSize.Height += itemGap;
                }
                magnifierPosition = totalSize.Height;

                magnifier       = Magnifier(Image, mousePos, Config.MagnifierPixelCount, Config.MagnifierPixelCount, Config.MagnifierPixelSize);
                totalSize.Width = Math.Max(totalSize.Width, magnifier.Width);

                totalSize.Height += magnifier.Height;
                itemCount++;
            }

            int       infoTextPadding  = 3;
            int       infoTextPosition = 0;
            Rectangle infoTextRect     = Rectangle.Empty;
            string    infoText         = "";

            if (Config.ShowInfo)
            {
                if (itemCount > 0)
                {
                    totalSize.Height += itemGap;
                }
                infoTextPosition = totalSize.Height;

                CurrentPosition = InputManager.MousePosition;
                infoText        = GetInfoText();
                Size textSize = g.MeasureString(infoText, infoFont).ToSize();
                infoTextRect.Size = new Size(textSize.Width + infoTextPadding * 2, textSize.Height + infoTextPadding * 2);
                totalSize.Width   = Math.Max(totalSize.Width, infoTextRect.Width);

                totalSize.Height += infoTextRect.Height;
                itemCount++;
            }

            int x = mousePos.X + cursorOffsetX;

            if (x + totalSize.Width > currentScreenRect0Based.Right)
            {
                x = mousePos.X - cursorOffsetX - totalSize.Width;
            }

            int y = mousePos.Y + cursorOffsetY;

            if (y + totalSize.Height > currentScreenRect0Based.Bottom)
            {
                y = mousePos.Y - cursorOffsetY - totalSize.Height;
            }

            if (Config.ShowMagnifier)
            {
                using (GraphicsQualityManager quality = new GraphicsQualityManager(g))
                    using (TextureBrush brush = new TextureBrush(magnifier))
                    {
                        brush.TranslateTransform(x, y + magnifierPosition);

                        if (Config.UseSquareMagnifier)
                        {
                            g.FillRectangle(brush, x, y + magnifierPosition, magnifier.Width, magnifier.Height);
                            g.DrawRectangleProper(Pens.White, x - 1, y + magnifierPosition - 1, magnifier.Width + 2, magnifier.Height + 2);
                            g.DrawRectangleProper(Pens.Black, x, y + magnifierPosition, magnifier.Width, magnifier.Height);
                        }
                        else
                        {
                            g.FillEllipse(brush, x, y + magnifierPosition, magnifier.Width, magnifier.Height);
                            g.DrawEllipse(Pens.White, x - 1, y + magnifierPosition - 1, magnifier.Width + 2 - 1, magnifier.Height + 2 - 1);
                            g.DrawEllipse(Pens.Black, x, y + magnifierPosition, magnifier.Width - 1, magnifier.Height - 1);
                        }
                    }
            }

            if (Config.ShowInfo)
            {
                infoTextRect.Location = new Point(x + (totalSize.Width / 2) - (infoTextRect.Width / 2), y + infoTextPosition);
                DrawInfoText(g, infoText, infoTextRect, infoFont, infoTextPadding);
            }
        }
Beispiel #10
0
        public Image GetResultImage()
        {
            if (Mode == RegionCaptureMode.Editor)
            {
                foreach (BaseShape shape in ShapeManager.Shapes)
                {
                    shape.Move(-ImageRectangle.X, -ImageRectangle.Y);
                }

                Image img = GetOutputImage();

                foreach (BaseShape shape in ShapeManager.Shapes)
                {
                    shape.Move(ImageRectangle.X, ImageRectangle.Y);
                }

                return(img);
            }
            else if (Result == RegionResult.Region || Result == RegionResult.LastRegion)
            {
                GraphicsPath gp;

                if (Result == RegionResult.LastRegion)
                {
                    gp = LastRegionFillPath;
                }
                else
                {
                    gp = regionFillPath;
                }

                using (Image img = GetOutputImage())
                {
                    return(RegionCaptureTasks.ApplyRegionPathToImage(img, gp));
                }
            }
            else if (Result == RegionResult.Fullscreen)
            {
                return(GetOutputImage());
            }
            else if (Result == RegionResult.Monitor)
            {
                Screen[] screens = Screen.AllScreens;

                if (MonitorIndex < screens.Length)
                {
                    Screen    screen     = screens[MonitorIndex];
                    Rectangle screenRect = CaptureHelpers.ScreenToClient(screen.Bounds);

                    using (Image img = GetOutputImage())
                    {
                        return(ImageHelpers.CropImage(img, screenRect));
                    }
                }
            }
            else if (Result == RegionResult.ActiveMonitor)
            {
                Rectangle activeScreenRect = CaptureHelpers.GetActiveScreenBounds0Based();

                using (Image img = GetOutputImage())
                {
                    return(ImageHelpers.CropImage(img, activeScreenRect));
                }
            }

            return(null);
        }
Beispiel #11
0
        // Must be called before show form
        public void Prepare(Image img)
        {
            Image = img;

            if (Mode == RegionCaptureMode.Editor)
            {
                Rectangle rect = CaptureHelpers.GetActiveScreenBounds0Based();

                if (Image.Width > rect.Width || Image.Height > rect.Height)
                {
                    rect = ScreenRectangle0Based;
                }

                ImageRectangle = new Rectangle(rect.X + rect.Width / 2 - Image.Width / 2, rect.Y + rect.Height / 2 - Image.Height / 2, Image.Width, Image.Height);

                using (Image background = ImageHelpers.DrawCheckers(ScreenRectangle0Based.Width, ScreenRectangle0Based.Height))
                    using (Graphics g = Graphics.FromImage(background))
                    {
                        g.DrawImage(Image, ImageRectangle);

                        backgroundBrush = new TextureBrush(background)
                        {
                            WrapMode = WrapMode.Clamp
                        };
                    }
            }
            else if (Config.UseDimming)
            {
                using (Bitmap darkBackground = (Bitmap)Image.Clone())
                    using (Graphics g = Graphics.FromImage(darkBackground))
                        using (Brush brush = new SolidBrush(Color.FromArgb(30, Color.Black)))
                        {
                            g.FillRectangle(brush, 0, 0, darkBackground.Width, darkBackground.Height);

                            backgroundBrush = new TextureBrush(darkBackground)
                            {
                                WrapMode = WrapMode.Clamp
                            };
                        }

                backgroundHighlightBrush = new TextureBrush(Image)
                {
                    WrapMode = WrapMode.Clamp
                };
            }
            else
            {
                backgroundBrush = new TextureBrush(Image)
                {
                    WrapMode = WrapMode.Clamp
                };
            }

            ShapeManager = new ShapeManager(this);
            ShapeManager.WindowCaptureMode = Config.DetectWindows;
            ShapeManager.IncludeControls   = Config.DetectControls;

            if (Mode == RegionCaptureMode.OneClick || ShapeManager.WindowCaptureMode)
            {
                IntPtr handle = Handle;

                TaskEx.Run(() =>
                {
                    WindowsRectangleList wla = new WindowsRectangleList();
                    wla.IgnoreHandle         = handle;
                    wla.IncludeChildWindows  = ShapeManager.IncludeControls;
                    ShapeManager.Windows     = wla.GetWindowInfoListAsync(5000);
                });
            }

            if (Config.UseCustomInfoText || Mode == RegionCaptureMode.ScreenColorPicker)
            {
                bmpBackgroundImage = new Bitmap(Image);
            }
        }
Beispiel #12
0
 public CompanionCubesForm()
 {
     StartPosition = FormStartPosition.Manual;
     Bounds        = CaptureHelpers.GetScreenWorkingArea();
     Shown        += CompanionCubesForm_Shown;
 }
        /// <summary>
        /// Crop shot or Selected Window captures
        /// </summary>
        /// <param name="myImage">Fullscreen image</param>
        /// <param name="windowMode">True = Selected window, False = Crop shot</param>
        public Crop(Image myImage, bool windowMode)
        {
            InitializeComponent();
            selectedWindowMode = windowMode;
            bmpClean           = new Bitmap(myImage);
            bmpBackground      = new Bitmap(bmpClean);
            bmpRegion          = new Bitmap(bmpClean);
            Bounds             = CaptureHelpers.GetScreenBounds();
            this.CursorPos     = this.PointToClient(Cursor.Position);
            rectIntersect.Size = new Size(Bounds.Width - 1, Bounds.Height - 1);
            SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
            CalculateBoundaryFromMousePosition();
            timer.Tick       += new EventHandler(TimerTick);
            windowCheck.Tick += new EventHandler(WindowCheckTick);

            if (selectedWindowMode)
            {
                captureObjects = Engine.ConfigUI.SelectedWindowCaptureObjects;
                myRectangle    = new DynamicRectangle(CaptureType.SELECTED_WINDOW);
                WindowsListAdvanced wla = new WindowsListAdvanced();
                wla.IgnoreWindows.Add(Handle);
                wla.IncludeChildWindows = captureObjects;
                windows = wla.GetWindowsRectangleList();
            }
            else
            {
                myRectangle = new DynamicRectangle(CaptureType.CROP);

                if (Engine.ConfigUI.UseHardwareCursor)
                {
                    Cursor = Cursors.Cross;
                }
                else
                {
                    Cursor.Hide();
                }
            }

            using (Graphics gBackground = Graphics.FromImage(bmpBackground))
                using (Graphics gRegion = Graphics.FromImage(bmpRegion))
                {
                    gBackground.SmoothingMode = SmoothingMode.HighQuality;
                    gRegion.SmoothingMode     = SmoothingMode.HighQuality;

                    if ((selectedWindowMode && Engine.ConfigUI.SelectedWindowRegionStyles == RegionStyles.REGION_TRANSPARENT) ||
                        (!selectedWindowMode && Engine.ConfigUI.CropRegionStyles == RegionStyles.REGION_TRANSPARENT))
                    { // If Region Transparent
                        gRegion.FillRectangle(new SolidBrush(Color.FromArgb(Engine.ConfigUI.RegionTransparentValue, Color.White)),
                                              new Rectangle(0, 0, bmpRegion.Width, bmpRegion.Height));
                    }
                    else if ((selectedWindowMode && Engine.ConfigUI.SelectedWindowRegionStyles == RegionStyles.REGION_BRIGHTNESS) ||
                             (!selectedWindowMode && Engine.ConfigUI.CropRegionStyles == RegionStyles.REGION_BRIGHTNESS))
                    { // If Region Brightness
                        ImageAttributes imgattr = new ImageAttributes();
                        imgattr.SetColorMatrix(ColorMatrices.BrightnessFilter(Engine.ConfigUI.RegionBrightnessValue));
                        gRegion.DrawImage(bmpClean, new Rectangle(0, 0, bmpRegion.Width, bmpRegion.Height), 0, 0,
                                          bmpRegion.Width, bmpRegion.Height, GraphicsUnit.Pixel, imgattr);
                    }
                    else if ((selectedWindowMode && Engine.ConfigUI.SelectedWindowRegionStyles == RegionStyles.BACKGROUND_REGION_TRANSPARENT) ||
                             (!selectedWindowMode && Engine.ConfigUI.CropRegionStyles == RegionStyles.BACKGROUND_REGION_TRANSPARENT))
                    { // If Background Region Transparent
                        gBackground.FillRectangle(new SolidBrush(Color.FromArgb(Engine.ConfigUI.BackgroundRegionTransparentValue, Color.White)),
                                                  new Rectangle(0, 0, bmpBackground.Width, bmpBackground.Height));
                    }
                    else if ((selectedWindowMode && Engine.ConfigUI.SelectedWindowRegionStyles == RegionStyles.BACKGROUND_REGION_BRIGHTNESS) ||
                             (!selectedWindowMode && Engine.ConfigUI.CropRegionStyles == RegionStyles.BACKGROUND_REGION_BRIGHTNESS))
                    { // If Background Region Brightness
                        ImageAttributes imgattr = new ImageAttributes();
                        imgattr.SetColorMatrix(ColorMatrices.BrightnessFilter(Engine.ConfigUI.BackgroundRegionBrightnessValue));
                        gBackground.DrawImage(bmpClean, new Rectangle(0, 0, bmpBackground.Width, bmpBackground.Height), 0, 0,
                                              bmpBackground.Width, bmpBackground.Height, GraphicsUnit.Pixel, imgattr);
                    }
                    else if ((selectedWindowMode && Engine.ConfigUI.SelectedWindowRegionStyles == RegionStyles.BACKGROUND_REGION_GRAYSCALE) ||
                             (!selectedWindowMode && Engine.ConfigUI.CropRegionStyles == RegionStyles.BACKGROUND_REGION_GRAYSCALE))
                    { // If Background Region Grayscale
                        ImageAttributes imgattr = new ImageAttributes();
                        imgattr.SetColorMatrix(ColorMatrices.GrayscaleFilter());
                        gBackground.DrawImage(bmpClean, new Rectangle(0, 0, bmpBackground.Width, bmpBackground.Height), 0, 0,
                                              bmpBackground.Width, bmpBackground.Height, GraphicsUnit.Pixel, imgattr);
                    }
                }

            brushClean      = new TextureBrush(bmpClean);
            brushBackground = new TextureBrush(bmpBackground);
            brushRegion     = new TextureBrush(bmpRegion);
        }
Beispiel #14
0
        public void Update()
        {
            BaseShape shape = shapeManager.CurrentShape;

            if (shape != null && Visible && nodes != null)
            {
                if (InputManager.IsMouseDown(MouseButtons.Left))
                {
                    if (shape.NodeType == NodeType.Rectangle)
                    {
                        for (int i = 0; i < 8; i++)
                        {
                            if (nodes[i].IsDragging)
                            {
                                IsResizing = true;

                                if (!InputManager.IsBeforeMouseDown(MouseButtons.Left))
                                {
                                    tempRect = shape.Rectangle;
                                }

                                NodePosition nodePosition = (NodePosition)i;

                                int x = InputManager.MouseVelocity.X;

                                switch (nodePosition)
                                {
                                case NodePosition.TopLeft:
                                case NodePosition.Left:
                                case NodePosition.BottomLeft:
                                    tempRect.X     += x;
                                    tempRect.Width -= x;
                                    break;

                                case NodePosition.TopRight:
                                case NodePosition.Right:
                                case NodePosition.BottomRight:
                                    tempRect.Width += x;
                                    break;
                                }

                                int y = InputManager.MouseVelocity.Y;

                                switch (nodePosition)
                                {
                                case NodePosition.TopLeft:
                                case NodePosition.Top:
                                case NodePosition.TopRight:
                                    tempRect.Y      += y;
                                    tempRect.Height -= y;
                                    break;

                                case NodePosition.BottomLeft:
                                case NodePosition.Bottom:
                                case NodePosition.BottomRight:
                                    tempRect.Height += y;
                                    break;
                                }

                                shape.Rectangle = CaptureHelpers.FixRectangle(tempRect);

                                break;
                            }
                        }
                    }
                    else if (shape.NodeType == NodeType.Line)
                    {
                        if (nodes[(int)NodePosition.TopLeft].IsDragging)
                        {
                            IsResizing = true;

                            shape.StartPosition = new Point(InputManager.MousePosition0Based.X, InputManager.MousePosition0Based.Y);
                        }
                        else if (nodes[(int)NodePosition.BottomRight].IsDragging)
                        {
                            IsResizing = true;

                            shape.EndPosition = new Point(InputManager.MousePosition0Based.X, InputManager.MousePosition0Based.Y);
                        }
                    }
                }
                else
                {
                    IsResizing = false;
                }

                UpdateNodePositions();
            }
        }
Beispiel #15
0
        public void Update()
        {
            if (Visible && nodes != null)
            {
                if (InputManager.IsMouseDown(MouseButtons.Left))
                {
                    for (int i = 0; i < 8; i++)
                    {
                        if (nodes[i].IsDragging)
                        {
                            IsResizing = true;

                            if (!InputManager.IsBeforeMouseDown(MouseButtons.Left))
                            {
                                tempRect = areaManager.CurrentArea;
                            }

                            NodePosition nodePosition = (NodePosition)i;

                            int x = InputManager.MouseVelocity.X;

                            switch (nodePosition)
                            {
                            case NodePosition.TopLeft:
                            case NodePosition.Left:
                            case NodePosition.BottomLeft:
                                tempRect.X     += x;
                                tempRect.Width -= x;
                                break;

                            case NodePosition.TopRight:
                            case NodePosition.Right:
                            case NodePosition.BottomRight:
                                tempRect.Width += x;
                                break;
                            }

                            int y = InputManager.MouseVelocity.Y;

                            switch (nodePosition)
                            {
                            case NodePosition.TopLeft:
                            case NodePosition.Top:
                            case NodePosition.TopRight:
                                tempRect.Y      += y;
                                tempRect.Height -= y;
                                break;

                            case NodePosition.BottomLeft:
                            case NodePosition.Bottom:
                            case NodePosition.BottomRight:
                                tempRect.Height += y;
                                break;
                            }

                            areaManager.CurrentArea = CaptureHelpers.FixRectangle(tempRect);

                            break;
                        }
                    }
                }
                else
                {
                    IsResizing = false;
                }

                UpdateNodePositions();
            }
        }
Beispiel #16
0
 private void timer_Tick(object sender, EventArgs e)
 {
     CurrentMousePosition = CaptureHelpers.GetCursorPosition();
     SelectionRectangle   = CaptureHelpers.CreateRectangle(positionOnClick.X, positionOnClick.Y, CurrentMousePosition.X, CurrentMousePosition.Y);
     Refresh();
 }
Beispiel #17
0
        protected override void Draw(Graphics g)
        {
            if (AreaManager.IsCreating && AreaManager.IsSnapResizing)
            {
                foreach (Size size in Config.SnapSizes)
                {
                    Rectangle snapRect = CaptureHelpers.CalculateNewRectangle(AreaManager.PositionOnClick, AreaManager.CurrentPosition, size);
                    g.DrawRectangleProper(markerPen, snapRect);
                }
            }

            List <RegionInfo> areas = AreaManager.ValidAreas.ToList();
            bool drawAreaExist      = areas.Count > 0;

            if (AreaManager.IsCurrentHoverAreaValid && areas.All(area => area.Area != AreaManager.CurrentHoverArea))
            {
                areas.Add(AreaManager.GetRegionInfo(AreaManager.CurrentHoverArea));
            }

            if (areas.Count > 0)
            {
                UpdateRegionPath();

                if (drawAreaExist)
                {
                    if (Config.UseDimming)
                    {
                        using (Region region = new Region(regionDrawPath))
                        {
                            g.Clip = region;
                            g.FillRectangle(lightBackgroundBrush, ScreenRectangle0Based);
                            g.ResetClip();
                        }
                    }

                    using (Pen blinkBorderPen = new Pen(colorBlinkAnimation.GetColor()))
                    {
                        g.DrawPath(blinkBorderPen, regionDrawPath);
                    }

                    /*
                     * if (areas.Count > 1)
                     * {
                     *  Rectangle totalArea = AreaManager.CombineAreas();
                     *  g.DrawCrossRectangle(borderPen, totalArea, 15);
                     *
                     *  if (Config.ShowInfo)
                     *  {
                     *      ImageHelpers.DrawTextWithOutline(g, string.Format("X: {0} / Y: {1} / W: {2} / H: {3}", totalArea.X, totalArea.Y,
                     *          totalArea.Width, totalArea.Height), new PointF(totalArea.X + 5, totalArea.Y - 25), textFont, Color.White, Color.Black);
                     *  }
                     * }
                     */
                }

                if (AreaManager.IsCurrentHoverAreaValid)
                {
                    using (GraphicsPath hoverDrawPath = new GraphicsPath {
                        FillMode = FillMode.Winding
                    })
                    {
                        AddShapePath(hoverDrawPath, AreaManager.GetRegionInfo(AreaManager.CurrentHoverArea), -1);

                        g.DrawPath(borderPen, hoverDrawPath);
                        g.DrawPath(borderDotPen, hoverDrawPath);
                    }
                }

                if (AreaManager.IsCurrentAreaValid)
                {
                    g.DrawRectangleProper(borderPen, AreaManager.CurrentArea);
                    g.DrawRectangleProper(borderDotPen, AreaManager.CurrentArea);
                    DrawObjects(g);

                    if (RulerMode)
                    {
                        DrawRuler(g, AreaManager.CurrentArea, borderPen, 5, 10);
                        DrawRuler(g, AreaManager.CurrentArea, borderPen, 15, 100);

                        Point centerPos = new Point(AreaManager.CurrentArea.X + AreaManager.CurrentArea.Width / 2, AreaManager.CurrentArea.Y + AreaManager.CurrentArea.Height / 2);
                        int   markSize  = 10;
                        g.DrawLine(borderPen, centerPos.X, centerPos.Y - markSize, centerPos.X, centerPos.Y + markSize);
                        g.DrawLine(borderPen, centerPos.X - markSize, centerPos.Y, centerPos.X + markSize, centerPos.Y);
                    }
                }

                if (Config.ShowInfo)
                {
                    foreach (RegionInfo regionInfo in areas)
                    {
                        if (regionInfo.Area.IsValid())
                        {
                            string areaText = GetAreaText(regionInfo.Area);
                            DrawAreaText(g, areaText, regionInfo.Area);
                        }
                    }
                }
            }

            if (Config.ShowTips)
            {
                DrawTips(g, 10, 10);
            }

            if (Config.ShowMagnifier)
            {
                DrawMagnifier(g);
            }

            if (Config.ShowCrosshair)
            {
                DrawCrosshair(g);
            }
        }
        private void ZScreen_Load(object sender, EventArgs e)
        {
            Engine.zHandle = Handle;

            #region Window Size/Location

            if (Engine.ConfigApp.WindowLocation.IsEmpty)
            {
                Engine.ConfigApp.WindowLocation = Location;
            }

            if (Engine.ConfigApp.WindowSize.IsEmpty)
            {
                Engine.ConfigApp.WindowSize = Size;
            }

            if (Engine.ConfigApp.SaveFormSizePosition)
            {
                Rectangle screenRect = CaptureHelpers.GetScreenBounds();
                screenRect.Inflate(-100, -100);

                if (
                    screenRect.IntersectsWith(new Rectangle(Engine.ConfigApp.WindowLocation, Engine.ConfigApp.WindowSize)))
                {
                    Size     = Engine.ConfigApp.WindowSize;
                    Location = Engine.ConfigApp.WindowLocation;
                }
            }

            #endregion Window Size/Location

            #region Window Show/Hide

            bool bHideWindow = false;
            if (Engine.ConfigApp.ShowMainWindow)
            {
                if (Engine.ConfigApp.WindowState == FormWindowState.Maximized)
                {
                    WindowState = FormWindowState.Maximized;
                }
                else
                {
                    WindowState = FormWindowState.Normal;
                }
                ShowInTaskbar = Engine.ConfigApp.ShowInTaskbar;
            }
            else if (Engine.ConfigApp.ShowInTaskbar &&
                     Engine.ConfigApp.WindowButtonActionClose == WindowButtonAction.MinimizeToTaskbar)
            {
                WindowState = FormWindowState.Minimized;
            }
            else
            {
                bHideWindow = true;
            }

            if (Engine.ConfigApp.Windows7TaskbarIntegration && Engine.HasWindows7)
            {
                ZScreen_Windows7onlyTasks();
            }

            if (bHideWindow)
            {
                Hide(); // this should happen after windows 7 taskbar integration
            }

            #endregion Window Show/Hide

            LoggerTimer timer = Engine.EngineLogger.StartTimer(new StackFrame().GetMethod().Name + " started");

            ZScreen_Preconfig();

            mDebug = new ZScreenDebugHelper();
            mDebug.GetDebugInfo += debug_GetDebugInfo;

            SetToolTip(nudScreenshotDelay);

            new RichTextBoxMenu(rtbDebugLog, true);
            new RichTextBoxMenu(rtbStats, true);

            if (Engine.IsMultiInstance)
            {
                niTray.ShowBalloonTip(2000, Engine.GetProductName(),
                                      string.Format("Another instance of {0} is already running...",
                                                    Application.ProductName), ToolTipIcon.Warning);
                niTray.BalloonTipClicked += niTray2_BalloonTipClicked;
            }

            timer.WriteLineTime(new StackFrame().GetMethod().Name + " finished");

            Application.Idle += Application_Idle;
        }
Beispiel #19
0
 private void btnFullscreen_Click(object sender, EventArgs e)
 {
     Program.Settings.AutoCaptureRegion = CaptureHelpers.GetScreenBounds();
     UpdateRegion();
 }
Beispiel #20
0
        private static void StartRecording(ScreenRecordOutput outputType, TaskSettings taskSettings, ScreenRecordStartMethod startMethod = ScreenRecordStartMethod.Region)
        {
            if (outputType == ScreenRecordOutput.FFmpeg && taskSettings.CaptureSettings.FFmpegOptions.VideoCodec == FFmpegVideoCodec.gif)
            {
                outputType = ScreenRecordOutput.GIF;
            }

            if (outputType == ScreenRecordOutput.FFmpeg)
            {
                DebugHelper.WriteLine("Starting screen recording. Video encoder: \"{0}\", Audio encoder: \"{1}\", FPS: {2}",
                                      taskSettings.CaptureSettings.FFmpegOptions.VideoCodec.GetDescription(), taskSettings.CaptureSettings.FFmpegOptions.AudioCodec.GetDescription(),
                                      taskSettings.CaptureSettings.ScreenRecordFPS);
            }
            else
            {
                DebugHelper.WriteLine("Starting screen recording. FPS: {0}", taskSettings.CaptureSettings.GIFFPS);
            }

            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_There_is_no_valid_CLI_video_encoder_selected_,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_CLI_video_encoder_file_does_not_exist__ +
                                    Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (outputType == ScreenRecordOutput.GIF)
            {
                taskSettings.CaptureSettings.FFmpegOptions.VideoCodec        = FFmpegVideoCodec.gif;
                taskSettings.CaptureSettings.FFmpegOptions.UseCustomCommands = false;
            }

            if (!TaskHelpers.CheckFFmpeg(taskSettings))
            {
                return;
            }

            if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
            {
                MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Rectangle captureRectangle = Rectangle.Empty;

            switch (startMethod)
            {
            case ScreenRecordStartMethod.Region:
                RegionCaptureTasks.GetRectangleRegion(out captureRectangle, taskSettings.CaptureSettings.SurfaceOptions);
                break;

            case ScreenRecordStartMethod.ActiveWindow:
                if (taskSettings.CaptureSettings.CaptureClientArea)
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowClientRectangle();
                }
                else
                {
                    captureRectangle = CaptureHelpers.GetActiveWindowRectangle();
                }
                break;

            case ScreenRecordStartMethod.CustomRegion:
                captureRectangle = taskSettings.CaptureSettings.CaptureCustomRegion;
                break;

            case ScreenRecordStartMethod.LastRegion:
                captureRectangle = Program.Settings.ScreenRecordRegion;
                break;
            }

            Rectangle screenRectangle = CaptureHelpers.GetScreenBounds();

            captureRectangle = Rectangle.Intersect(captureRectangle, screenRectangle);

            if (outputType != ScreenRecordOutput.GIF)
            {
                captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);
            }

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;

            string path           = "";
            bool   abortRequested = false;

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            recordForm = new ScreenRecordForm(captureRectangle, startMethod == ScreenRecordStartMethod.Region, duration);
            recordForm.StopRequested += StopRecording;
            recordForm.Show();

            TaskEx.Run(() =>
            {
                try
                {
                    string filename = TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension);
                    path            = TaskHelpers.CheckFilePath(taskSettings.CaptureFolder, filename, taskSettings);

                    if (string.IsNullOrEmpty(path))
                    {
                        abortRequested = true;
                    }

                    if (!abortRequested)
                    {
                        recordForm.ChangeState(ScreenRecordState.BeforeStart);

                        if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                        {
                            int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                            if (delay > 0)
                            {
                                recordForm.InvokeSafe(() => recordForm.StartCountdown(delay));

                                recordForm.RecordResetEvent.WaitOne(delay);
                            }
                        }
                        else
                        {
                            recordForm.RecordResetEvent.WaitOne();
                        }

                        if (recordForm.IsAbortRequested)
                        {
                            abortRequested = true;
                        }

                        if (!abortRequested)
                        {
                            ScreencastOptions options = new ScreencastOptions()
                            {
                                FFmpeg          = taskSettings.CaptureSettings.FFmpegOptions,
                                ScreenRecordFPS = taskSettings.CaptureSettings.ScreenRecordFPS,
                                GIFFPS          = taskSettings.CaptureSettings.GIFFPS,
                                Duration        = duration,
                                OutputPath      = path,
                                CaptureArea     = captureRectangle,
                                DrawCursor      = taskSettings.CaptureSettings.ScreenRecordShowCursor
                            };

                            Screenshot screenshot    = TaskHelpers.GetScreenshot(taskSettings);
                            screenshot.CaptureCursor = taskSettings.CaptureSettings.ScreenRecordShowCursor;

                            screenRecorder = new ScreenRecorder(ScreenRecordOutput.FFmpeg, options, screenshot, captureRectangle);
                            screenRecorder.RecordingStarted += () => recordForm.ChangeState(ScreenRecordState.AfterRecordingStart);
                            recordForm.ChangeState(ScreenRecordState.AfterStart);
                            screenRecorder.StartRecording();

                            if (recordForm.IsAbortRequested)
                            {
                                abortRequested = true;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }

                try
                {
                    if (!abortRequested && screenRecorder != null && File.Exists(path))
                    {
                        recordForm.ChangeState(ScreenRecordState.AfterStop);

                        string sourceFilePath = path;

                        if (outputType == ScreenRecordOutput.GIF)
                        {
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            screenRecorder.FFmpegEncodeAsGIF(sourceFilePath, path, Program.ToolsFolder);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (recordForm != null)
                    {
                        recordForm.InvokeSafe(() =>
                        {
                            recordForm.Close();
                            recordForm.Dispose();
                            recordForm = null;
                        });
                    }

                    if (screenRecorder != null)
                    {
                        if ((outputType == ScreenRecordOutput.GIF || taskSettings.CaptureSettings.RunScreencastCLI) &&
                            !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;

                        if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                }
            },
                       () =>
            {
                string customFileName;

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings, out customFileName, null, path))
                {
                    if (!string.IsNullOrEmpty(customFileName))
                    {
                        string currentFilename = Path.GetFileNameWithoutExtension(path);
                        string ext             = Path.GetExtension(path);

                        if (!currentFilename.Equals(customFileName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            path = Helpers.RenameFile(path, customFileName + ext);
                        }
                    }

                    WorkerTask task = WorkerTask.CreateFileJobTask(path, taskSettings, customFileName);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
Beispiel #21
0
        private static void Task_TaskCompleted(WorkerTask task)
        {
            try
            {
                task.KeepImage = false;

                if (task != null)
                {
                    if (task.RequestSettingUpdate)
                    {
                        Program.MainForm.UpdateCheckStates();
                    }

                    TaskInfo info = task.Info;

                    if (info != null && info.Result != null)
                    {
                        TaskThumbnailPanel panel = TaskThumbnailView.FindPanel(task);

                        if (panel != null)
                        {
                            panel.UpdateStatus();
                            panel.ProgressVisible = false;
                        }

                        ListViewItem lvi = TaskListView.FindItem(task);

                        if (task.Status == TaskStatus.Stopped)
                        {
                            DebugHelper.WriteLine($"Task stopped. Filename: {info.FileName}");

                            if (lvi != null)
                            {
                                lvi.Text             = info.FileName;
                                lvi.SubItems[1].Text = info.Status;
                                lvi.ImageIndex       = 2;
                            }
                        }
                        else if (task.Status == TaskStatus.Failed)
                        {
                            string errors = string.Join("\r\n\r\n", info.Result.Errors.ToArray());

                            DebugHelper.WriteLine($"Task failed. Filename: {info.FileName}, Errors:\r\n{errors}");

                            if (lvi != null)
                            {
                                lvi.SubItems[1].Text = info.Status;
                                lvi.SubItems[6].Text = "";
                                lvi.ImageIndex       = 1;
                            }

                            if (!info.TaskSettings.AdvancedSettings.DisableNotifications)
                            {
                                if (info.TaskSettings.GeneralSettings.PlaySoundAfterUpload)
                                {
                                    TaskHelpers.PlayErrorSound(info.TaskSettings);
                                }

                                if (info.TaskSettings.GeneralSettings.PopUpNotification != PopUpNotificationType.None && !string.IsNullOrEmpty(errors) &&
                                    (!info.TaskSettings.AdvancedSettings.DisableNotificationsOnFullscreen || !CaptureHelpers.IsActiveWindowFullscreen()))
                                {
                                    TaskHelpers.ShowBalloonTip(errors, ToolTipIcon.Error, 5000, "ShareX - " + Resources.TaskManager_task_UploadCompleted_Error);
                                }
                            }
                        }
                        else
                        {
                            DebugHelper.WriteLine($"Task completed. Filename: {info.FileName}, Duration: {(long)info.TaskDuration.TotalMilliseconds} ms");

                            string result = info.Result.ToString();

                            if (string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(info.FilePath))
                            {
                                result = info.FilePath;
                            }

                            if (lvi != null)
                            {
                                lvi.Text             = info.FileName;
                                lvi.SubItems[1].Text = info.Status;
                                lvi.ImageIndex       = 2;

                                if (!string.IsNullOrEmpty(result))
                                {
                                    lvi.SubItems[6].Text = result;
                                }
                            }

                            if (!task.StopRequested && !string.IsNullOrEmpty(result))
                            {
                                if (Program.Settings.HistorySaveTasks && (!Program.Settings.HistoryCheckURL ||
                                                                          (!string.IsNullOrEmpty(info.Result.URL) || !string.IsNullOrEmpty(info.Result.ShortenedURL))))
                                {
                                    HistoryItem historyItem = info.GetHistoryItem();
                                    AppendHistoryItemAsync(historyItem);
                                }

                                RecentManager.Add(task);

                                if (!info.TaskSettings.AdvancedSettings.DisableNotifications && info.Job != TaskJob.ShareURL)
                                {
                                    if (info.TaskSettings.GeneralSettings.PlaySoundAfterUpload)
                                    {
                                        TaskHelpers.PlayTaskCompleteSound(info.TaskSettings);
                                    }

                                    if (!string.IsNullOrEmpty(info.TaskSettings.AdvancedSettings.BalloonTipContentFormat))
                                    {
                                        result = new UploadInfoParser().Parse(info, info.TaskSettings.AdvancedSettings.BalloonTipContentFormat);
                                    }

                                    if (!string.IsNullOrEmpty(result) &&
                                        (!info.TaskSettings.AdvancedSettings.DisableNotificationsOnFullscreen || !CaptureHelpers.IsActiveWindowFullscreen()))
                                    {
                                        switch (info.TaskSettings.GeneralSettings.PopUpNotification)
                                        {
                                        case PopUpNotificationType.BalloonTip:
                                            BalloonTipAction action = new BalloonTipAction()
                                            {
                                                ClickAction = BalloonTipClickAction.OpenURL,
                                                Text        = result
                                            };

                                            TaskHelpers.ShowBalloonTip(result, ToolTipIcon.Info, 5000,
                                                                       "ShareX - " + Resources.TaskManager_task_UploadCompleted_ShareX___Task_completed, action);
                                            break;

                                        case PopUpNotificationType.ToastNotification:
                                            task.KeepImage = true;

                                            NotificationFormConfig toastConfig = new NotificationFormConfig()
                                            {
                                                LeftClickAction   = info.TaskSettings.AdvancedSettings.ToastWindowClickAction,
                                                RightClickAction  = info.TaskSettings.AdvancedSettings.ToastWindowRightClickAction,
                                                MiddleClickAction = info.TaskSettings.AdvancedSettings.ToastWindowMiddleClickAction,
                                                FilePath          = info.FilePath,
                                                Image             = task.Image,
                                                Text = "ShareX - " + Resources.TaskManager_task_UploadCompleted_ShareX___Task_completed + "\r\n" + result,
                                                URL  = result
                                            };
                                            NotificationForm.Show((int)(info.TaskSettings.AdvancedSettings.ToastWindowDuration * 1000),
                                                                  (int)(info.TaskSettings.AdvancedSettings.ToastWindowFadeDuration * 1000),
                                                                  info.TaskSettings.AdvancedSettings.ToastWindowPlacement,
                                                                  info.TaskSettings.AdvancedSettings.ToastWindowSize, toastConfig);
                                            break;
                                        }

                                        if (info.TaskSettings.AfterUploadJob.HasFlag(AfterUploadTasks.ShowAfterUploadWindow) && info.IsUploadJob)
                                        {
                                            AfterUploadForm dlg = new AfterUploadForm(info);
                                            NativeMethods.ShowWindow(dlg.Handle, (int)WindowShowStyle.ShowNoActivate);
                                        }
                                    }
                                }
                            }
                        }

                        if (lvi != null)
                        {
                            lvi.EnsureVisible();

                            if (Program.Settings.AutoSelectLastCompletedTask)
                            {
                                TaskListView.ListViewControl.SelectSingle(lvi);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (!IsBusy && Program.CLI.IsCommandExist("AutoClose"))
                {
                    Application.Exit();
                }
                else
                {
                    StartTasks();
                    UpdateProgressUI();

                    if (Program.Settings.SaveSettingsAfterTaskCompleted && !IsBusy)
                    {
                        SettingManager.SaveAllSettingsAsync();
                    }
                }
            }
        }
Beispiel #22
0
        public Image CaptureActiveMonitor()
        {
            Rectangle bounds = CaptureHelpers.GetActiveScreenBounds();

            return(CaptureRectangle(bounds));
        }
Beispiel #23
0
        public void StartRecording(TaskSettings taskSettings)
        {
            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show("There is no valid CLI video encoder selected.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show("CLI video encoder file does not exist: " + Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (taskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.FFmpeg && !File.Exists(taskSettings.CaptureSettings.FFmpegOptions.CLIPath))
            {
                string ffmpegText = string.IsNullOrEmpty(taskSettings.CaptureSettings.FFmpegOptions.CLIPath) ? "ffmpeg.exe" : taskSettings.CaptureSettings.FFmpegOptions.CLIPath;

                if (MessageBox.Show(ffmpegText + " does not exist." + Environment.NewLine + Environment.NewLine + "Would you like to automatically download it?",
                                    Application.ProductName + " - Missing ffmpeg.exe", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    if (FFmpegHelper.DownloadFFmpeg(false, DownloaderForm_InstallRequested) == DialogResult.OK)
                    {
                        Program.DefaultTaskSettings.CaptureSettings.FFmpegOptions.CLIPath = taskSettings.TaskSettingsReference.CaptureSettings.FFmpegOptions.CLIPath =
                            taskSettings.CaptureSettings.FFmpegOptions.CLIPath            = Path.Combine(Program.ToolsFolder, "ffmpeg.exe");
                    }
                }
                else
                {
                    return;
                }
            }

            if (taskSettings.AdvancedSettings.ScreenRecorderUseActiveWindow)
            {
                ActiveWindowRegion(taskSettings);
            }
            else
            {
                SelectRegion();
            }

            captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            IsRecording = true;
            Screenshot.CaptureCursor = taskSettings.CaptureSettings.ShowCursor;

            TrayIcon.Text    = "ShareX - Waiting...";
            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            TrayIcon.Visible = true;

            string path = "";

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            regionForm = ScreenRegionForm.Show(captureRectangle, StopRecording, duration);

            TaskEx.Run(() =>
            {
                try
                {
                    if (taskSettings.CaptureSettings.ScreenRecordAutoDisableAero)
                    {
                        dwmManager = new DWMManager();
                        dwmManager.AutoDisable();
                    }

                    if (taskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVI)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "avi"));
                    }
                    else if (taskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.FFmpeg)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension));
                    }
                    else
                    {
                        path = Program.ScreenRecorderCacheFilePath;
                    }

                    ScreencastOptions options = new ScreencastOptions()
                    {
                        FFmpeg          = taskSettings.CaptureSettings.FFmpegOptions,
                        AVI             = taskSettings.CaptureSettings.AVIOptions,
                        ScreenRecordFPS = taskSettings.CaptureSettings.ScreenRecordFPS,
                        GIFFPS          = taskSettings.CaptureSettings.GIFFPS,
                        Duration        = duration,
                        OutputPath      = path,
                        CaptureArea     = captureRectangle,
                        DrawCursor      = taskSettings.CaptureSettings.ShowCursor
                    };

                    screenRecorder = new ScreenRecorder(options, captureRectangle, taskSettings.CaptureSettings.ScreenRecordOutput);

                    int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                    if (delay > 0)
                    {
                        Thread.Sleep(delay);
                    }

                    TrayIcon.Text = "ShareX - Click tray icon to stop recording.";
                    TrayIcon.Icon = Resources.control_record.ToIcon();

                    if (regionForm != null)
                    {
                        this.InvokeSafe(() => regionForm.StartTimer());
                    }

                    screenRecorder.StartRecording();
                }
                finally
                {
                    if (dwmManager != null)
                    {
                        dwmManager.Dispose();
                        dwmManager = null;
                    }

                    if (regionForm != null)
                    {
                        this.InvokeSafe(() => regionForm.Close());
                    }
                }

                try
                {
                    if (screenRecorder != null)
                    {
                        TrayIcon.Text = "ShareX - Encoding...";
                        TrayIcon.Icon = Resources.camcorder_pencil.ToIcon();

                        string sourceFilePath = path;

                        if (taskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.GIF)
                        {
                            if (taskSettings.CaptureSettings.RunScreencastCLI)
                            {
                                sourceFilePath = Path.ChangeExtension(Program.ScreenRecorderCacheFilePath, "gif");
                            }
                            else
                            {
                                sourceFilePath = path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            }

                            screenRecorder.SaveAsGIF(sourceFilePath, taskSettings.ImageSettings.ImageGIFQuality);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (screenRecorder != null)
                    {
                        if (taskSettings.CaptureSettings.RunScreencastCLI && !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;
                    }
                }
            },
                       () =>
            {
                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }

                IsRecording = false;

                if (!string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings))
                {
                    UploadTask task = UploadTask.CreateFileJobTask(path, taskSettings);
                    TaskManager.Start(task);
                }
            });
        }
Beispiel #24
0
        public Image CaptureFullscreen()
        {
            Rectangle bounds = CaptureHelpers.GetScreenBounds();

            return(CaptureRectangle(bounds));
        }
Beispiel #25
0
        private void CreateToolbar()
        {
            menuForm = new Form()
            {
                AutoScaleDimensions = new SizeF(6F, 13F),
                AutoScaleMode       = AutoScaleMode.Font,
                AutoSize            = true,
                AutoSizeMode        = AutoSizeMode.GrowAndShrink,
                ClientSize          = new Size(759, 509),
                FormBorderStyle     = FormBorderStyle.None,
                Location            = new Point(200, 200),
                ShowInTaskbar       = false,
                StartPosition       = FormStartPosition.Manual,
                Text    = "ShareX - Region capture menu",
                TopMost = true
            };

            menuForm.Shown           += MenuForm_Shown;
            menuForm.KeyDown         += MenuForm_KeyDown;
            menuForm.KeyUp           += MenuForm_KeyUp;
            menuForm.LocationChanged += MenuForm_LocationChanged;

            menuForm.SuspendLayout();

            tsMain = new ToolStripEx()
            {
                AutoSize         = true,
                CanOverflow      = false,
                ClickThrough     = true,
                Dock             = DockStyle.None,
                GripStyle        = ToolStripGripStyle.Hidden,
                Location         = new Point(0, 0),
                MinimumSize      = new Size(10, 30),
                Padding          = new Padding(0, 1, 0, 0),
                Renderer         = new CustomToolStripProfessionalRenderer(),
                TabIndex         = 0,
                ShowItemToolTips = false
            };

            tsMain.MouseLeave += TsMain_MouseLeave;

            tsMain.SuspendLayout();

            // https://www.medo64.com/2014/01/scaling-toolstrip-with-dpi/
            using (Graphics g = menuForm.CreateGraphics())
            {
                double scale    = Math.Max(g.DpiX, g.DpiY) / 96.0;
                double newScale = ((int)Math.Floor(scale * 100) / 25 * 25) / 100.0;
                if (newScale > 1)
                {
                    int newWidth  = (int)(tsMain.ImageScalingSize.Width * newScale);
                    int newHeight = (int)(tsMain.ImageScalingSize.Height * newScale);
                    tsMain.ImageScalingSize = new Size(newWidth, newHeight);
                }
            }

            menuForm.Controls.Add(tsMain);

            tslDragLeft = new ToolStripLabel()
            {
                DisplayStyle = ToolStripItemDisplayStyle.Image,
                Image        = Resources.ui_radio_button_uncheck,
                Margin       = new Padding(2, 0, 2, 0),
                Padding      = new Padding(2)
            };

            tsMain.Items.Add(tslDragLeft);

            if (form.IsEditorMode)
            {
                #region Editor mode

                ToolStripButton tsbCompleteEdit = new ToolStripButton();

                if (form.Mode == RegionCaptureMode.Editor)
                {
                    tsbCompleteEdit.Text = Resources.ShapeManager_CreateToolbar_RunAfterCaptureTasks;
                }
                else
                {
                    tsbCompleteEdit.Text = Resources.ShapeManager_CreateToolbar_ApplyChangesContinueTaskEnter;
                }

                tsbCompleteEdit.DisplayStyle = ToolStripItemDisplayStyle.Image;
                tsbCompleteEdit.Image        = Resources.tick;
                tsbCompleteEdit.MouseDown   += (sender, e) => form.Close(RegionResult.AnnotateRunAfterCaptureTasks);
                tsMain.Items.Add(tsbCompleteEdit);

                if (form.Mode == RegionCaptureMode.TaskEditor)
                {
                    ToolStripButton tsbClose = new ToolStripButton(Resources.ShapeManager_CreateToolbar_ContinueTaskSpaceOrRightClick);
                    tsbClose.DisplayStyle = ToolStripItemDisplayStyle.Image;
                    tsbClose.Image        = Resources.control;
                    tsbClose.MouseDown   += (sender, e) => form.Close(RegionResult.AnnotateContinueTask);
                    tsMain.Items.Add(tsbClose);

                    ToolStripButton tsbCloseCancel = new ToolStripButton(Resources.ShapeManager_CreateToolbar_CancelTaskEsc);
                    tsbCloseCancel.DisplayStyle = ToolStripItemDisplayStyle.Image;
                    tsbCloseCancel.Image        = Resources.cross;
                    tsbCloseCancel.MouseDown   += (sender, e) => form.Close(RegionResult.AnnotateCancelTask);
                    tsMain.Items.Add(tsbCloseCancel);
                }

                if (form.Mode == RegionCaptureMode.TaskEditor)
                {
                    tsMain.Items.Add(new ToolStripSeparator());
                }

                ToolStripButton tsbSaveImage = new ToolStripButton(Resources.ShapeManager_CreateToolbar_SaveImage);
                tsbSaveImage.DisplayStyle = ToolStripItemDisplayStyle.Image;
                tsbSaveImage.Enabled      = File.Exists(form.ImageFilePath);
                tsbSaveImage.Image        = Resources.disk_black;
                tsbSaveImage.MouseDown   += (sender, e) => form.Close(RegionResult.AnnotateSaveImage);
                tsMain.Items.Add(tsbSaveImage);

                ToolStripButton tsbSaveImageAs = new ToolStripButton(Resources.ShapeManager_CreateToolbar_SaveImageAs);
                tsbSaveImageAs.DisplayStyle = ToolStripItemDisplayStyle.Image;
                tsbSaveImageAs.Image        = Resources.disks_black;
                tsbSaveImageAs.MouseDown   += (sender, e) => form.Close(RegionResult.AnnotateSaveImageAs);
                tsMain.Items.Add(tsbSaveImageAs);

                ToolStripButton tsbCopyImage = new ToolStripButton(Resources.ShapeManager_CreateToolbar_CopyImageToClipboard);
                tsbCopyImage.DisplayStyle = ToolStripItemDisplayStyle.Image;
                tsbCopyImage.Image        = Resources.clipboard;
                tsbCopyImage.MouseDown   += (sender, e) => form.Close(RegionResult.AnnotateCopyImage);
                tsMain.Items.Add(tsbCopyImage);

                ToolStripButton tsbUploadImage = new ToolStripButton(Resources.ShapeManager_CreateToolbar_UploadImage);
                tsbUploadImage.DisplayStyle = ToolStripItemDisplayStyle.Image;
                tsbUploadImage.Image        = Resources.drive_globe;
                tsbUploadImage.MouseDown   += (sender, e) => form.Close(RegionResult.AnnotateUploadImage);
                tsMain.Items.Add(tsbUploadImage);

                ToolStripButton tsbPrintImage = new ToolStripButton(Resources.ShapeManager_CreateToolbar_PrintImage);
                tsbPrintImage.DisplayStyle = ToolStripItemDisplayStyle.Image;
                tsbPrintImage.Image        = Resources.printer;
                tsbPrintImage.MouseDown   += (sender, e) => form.Close(RegionResult.AnnotatePrintImage);
                tsMain.Items.Add(tsbPrintImage);

                tsMain.Items.Add(new ToolStripSeparator());

                #endregion Editor mode
            }

            #region Tools

            foreach (ShapeType shapeType in Helpers.GetEnums <ShapeType>())
            {
                if (form.IsEditorMode)
                {
                    if (IsShapeTypeRegion(shapeType))
                    {
                        continue;
                    }
                }
                else if (shapeType == ShapeType.DrawingRectangle)
                {
                    tsMain.Items.Add(new ToolStripSeparator());
                }
                else if (shapeType == ShapeType.DrawingCrop)
                {
                    continue;
                }

                ToolStripButton tsbShapeType = new ToolStripButton(shapeType.GetLocalizedDescription());
                tsbShapeType.DisplayStyle = ToolStripItemDisplayStyle.Image;

                Image img = null;

                switch (shapeType)
                {
                case ShapeType.RegionRectangle:
                    img = Resources.layer_shape_region;
                    break;

                case ShapeType.RegionEllipse:
                    img = Resources.layer_shape_ellipse_region;
                    break;

                case ShapeType.RegionFreehand:
                    img = Resources.layer_shape_polygon;
                    break;

                case ShapeType.DrawingRectangle:
                    img = Resources.layer_shape;
                    break;

                case ShapeType.DrawingEllipse:
                    img = Resources.layer_shape_ellipse;
                    break;

                case ShapeType.DrawingFreehand:
                    img = Resources.pencil;
                    break;

                case ShapeType.DrawingLine:
                    img = Resources.layer_shape_line;
                    break;

                case ShapeType.DrawingArrow:
                    img = Resources.layer_shape_arrow;
                    break;

                case ShapeType.DrawingTextOutline:
                    img = Resources.edit_outline;
                    break;

                case ShapeType.DrawingTextBackground:
                    img = Resources.edit_shade;
                    break;

                case ShapeType.DrawingSpeechBalloon:
                    img = Resources.balloon_box_left;
                    break;

                case ShapeType.DrawingStep:
                    img = Resources.counter_reset;
                    break;

                case ShapeType.DrawingImage:
                    img = Resources.folder_open_image;
                    break;

                case ShapeType.DrawingImageScreen:
                    img = Resources.monitor_image;
                    break;

                case ShapeType.DrawingCursor:
                    img = Resources.cursor;
                    break;

                case ShapeType.EffectBlur:
                    img = Resources.layer_shade;
                    break;

                case ShapeType.EffectPixelate:
                    img = Resources.grid;
                    break;

                case ShapeType.EffectHighlight:
                    img = Resources.highlighter_text;
                    break;

                case ShapeType.DrawingCrop:
                    img = Resources.image_crop;
                    break;
                }

                tsbShapeType.Image   = img;
                tsbShapeType.Checked = shapeType == CurrentShapeType;
                tsbShapeType.Tag     = shapeType;

                tsbShapeType.MouseDown += (sender, e) =>
                {
                    tsbShapeType.RadioCheck();
                    CurrentShapeType = shapeType;
                };

                tsMain.Items.Add(tsbShapeType);
            }

            #endregion Tools

            #region Shape options

            tsMain.Items.Add(new ToolStripSeparator());

            tsbBorderColor = new ToolStripButton(Resources.ShapeManager_CreateContextMenu_Border_color___);
            tsbBorderColor.DisplayStyle = ToolStripItemDisplayStyle.Image;
            tsbBorderColor.Click       += (sender, e) =>
            {
                PauseForm();

                ShapeType shapeType = CurrentShapeType;

                Color borderColor;

                if (shapeType == ShapeType.DrawingTextBackground || shapeType == ShapeType.DrawingSpeechBalloon)
                {
                    borderColor = AnnotationOptions.TextBorderColor;
                }
                else if (shapeType == ShapeType.DrawingTextOutline)
                {
                    borderColor = AnnotationOptions.TextOutlineBorderColor;
                }
                else if (shapeType == ShapeType.DrawingStep)
                {
                    borderColor = AnnotationOptions.StepBorderColor;
                }
                else
                {
                    borderColor = AnnotationOptions.BorderColor;
                }

                if (ColorPickerForm.PickColor(borderColor, out Color newColor))
                {
                    if (shapeType == ShapeType.DrawingTextBackground || shapeType == ShapeType.DrawingSpeechBalloon)
                    {
                        AnnotationOptions.TextBorderColor = newColor;
                    }
                    else if (shapeType == ShapeType.DrawingTextOutline)
                    {
                        AnnotationOptions.TextOutlineBorderColor = newColor;
                    }
                    else if (shapeType == ShapeType.DrawingStep)
                    {
                        AnnotationOptions.StepBorderColor = newColor;
                    }
                    else
                    {
                        AnnotationOptions.BorderColor = newColor;
                    }

                    UpdateMenu();
                    UpdateCurrentShape();
                }

                ResumeForm();
            };
            tsMain.Items.Add(tsbBorderColor);

            tsbFillColor = new ToolStripButton(Resources.ShapeManager_CreateContextMenu_Fill_color___);
            tsbFillColor.DisplayStyle = ToolStripItemDisplayStyle.Image;
            tsbFillColor.Click       += (sender, e) =>
            {
                PauseForm();

                ShapeType shapeType = CurrentShapeType;

                Color fillColor;

                if (shapeType == ShapeType.DrawingTextBackground || shapeType == ShapeType.DrawingSpeechBalloon)
                {
                    fillColor = AnnotationOptions.TextFillColor;
                }
                else if (shapeType == ShapeType.DrawingStep)
                {
                    fillColor = AnnotationOptions.StepFillColor;
                }
                else
                {
                    fillColor = AnnotationOptions.FillColor;
                }

                if (ColorPickerForm.PickColor(fillColor, out Color newColor))
                {
                    if (shapeType == ShapeType.DrawingTextBackground || shapeType == ShapeType.DrawingSpeechBalloon)
                    {
                        AnnotationOptions.TextFillColor = newColor;
                    }
                    else if (shapeType == ShapeType.DrawingStep)
                    {
                        AnnotationOptions.StepFillColor = newColor;
                    }
                    else
                    {
                        AnnotationOptions.FillColor = newColor;
                    }

                    UpdateMenu();
                    UpdateCurrentShape();
                }

                ResumeForm();
            };
            tsMain.Items.Add(tsbFillColor);

            tsbHighlightColor = new ToolStripButton(Resources.ShapeManager_CreateContextMenu_Highlight_color___);
            tsbHighlightColor.DisplayStyle = ToolStripItemDisplayStyle.Image;
            tsbHighlightColor.Click       += (sender, e) =>
            {
                PauseForm();

                if (ColorPickerForm.PickColor(AnnotationOptions.HighlightColor, out Color newColor))
                {
                    AnnotationOptions.HighlightColor = newColor;
                    UpdateMenu();
                    UpdateCurrentShape();
                }

                ResumeForm();
            };
            tsMain.Items.Add(tsbHighlightColor);

            tsddbShapeOptions = new ToolStripDropDownButton(Resources.ShapeManager_CreateToolbar_ShapeOptions);
            tsddbShapeOptions.DisplayStyle = ToolStripItemDisplayStyle.Image;
            tsddbShapeOptions.Image        = Resources.layer__pencil;
            tsMain.Items.Add(tsddbShapeOptions);

            tslnudBorderSize = new ToolStripLabeledNumericUpDown(Resources.ShapeManager_CreateContextMenu_Border_size_);
            tslnudBorderSize.Content.Minimum      = 0;
            tslnudBorderSize.Content.Maximum      = 20;
            tslnudBorderSize.Content.ValueChanged = (sender, e) =>
            {
                ShapeType shapeType = CurrentShapeType;

                int borderSize = (int)tslnudBorderSize.Content.Value;

                if (shapeType == ShapeType.DrawingTextBackground || shapeType == ShapeType.DrawingSpeechBalloon)
                {
                    AnnotationOptions.TextBorderSize = borderSize;
                }
                else if (shapeType == ShapeType.DrawingTextOutline)
                {
                    AnnotationOptions.TextOutlineBorderSize = borderSize;
                }
                else if (shapeType == ShapeType.DrawingStep)
                {
                    AnnotationOptions.StepBorderSize = borderSize;
                }
                else
                {
                    AnnotationOptions.BorderSize = borderSize;
                }

                UpdateCurrentShape();
            };
            tsddbShapeOptions.DropDownItems.Add(tslnudBorderSize);

            tslnudCornerRadius = new ToolStripLabeledNumericUpDown(Resources.ShapeManager_CreateContextMenu_Corner_radius_);
            tslnudCornerRadius.Content.Minimum      = 0;
            tslnudCornerRadius.Content.Maximum      = 150;
            tslnudCornerRadius.Content.ValueChanged = (sender, e) =>
            {
                ShapeType shapeType = CurrentShapeType;

                if (shapeType == ShapeType.RegionRectangle)
                {
                    AnnotationOptions.RegionCornerRadius = (int)tslnudCornerRadius.Content.Value;
                }
                else if (shapeType == ShapeType.DrawingRectangle || shapeType == ShapeType.DrawingTextBackground)
                {
                    AnnotationOptions.DrawingCornerRadius = (int)tslnudCornerRadius.Content.Value;
                }

                UpdateCurrentShape();
            };
            tsddbShapeOptions.DropDownItems.Add(tslnudCornerRadius);

            tslnudBlurRadius = new ToolStripLabeledNumericUpDown(Resources.ShapeManager_CreateContextMenu_Blur_radius_);
            tslnudBlurRadius.Content.Minimum      = 3;
            tslnudBlurRadius.Content.Maximum      = 199;
            tslnudBlurRadius.Content.Increment    = 2;
            tslnudBlurRadius.Content.ValueChanged = (sender, e) =>
            {
                AnnotationOptions.BlurRadius = (int)tslnudBlurRadius.Content.Value;
                UpdateCurrentShape();
            };
            tsddbShapeOptions.DropDownItems.Add(tslnudBlurRadius);

            tslnudPixelateSize = new ToolStripLabeledNumericUpDown(Resources.ShapeManager_CreateContextMenu_Pixel_size_);
            tslnudPixelateSize.Content.Minimum      = 2;
            tslnudPixelateSize.Content.Maximum      = 10000;
            tslnudPixelateSize.Content.ValueChanged = (sender, e) =>
            {
                AnnotationOptions.PixelateSize = (int)tslnudPixelateSize.Content.Value;
                UpdateCurrentShape();
            };
            tsddbShapeOptions.DropDownItems.Add(tslnudPixelateSize);

            tslnudCenterPoints = new ToolStripLabeledNumericUpDown("Center points:");
            tslnudCenterPoints.Content.Minimum      = 0;
            tslnudCenterPoints.Content.Maximum      = LineDrawingShape.MaximumCenterPointCount;
            tslnudCenterPoints.Content.ValueChanged = (sender, e) =>
            {
                AnnotationOptions.LineCenterPointCount = (int)tslnudCenterPoints.Content.Value;
                UpdateCurrentShape();
            };
            tsddbShapeOptions.DropDownItems.Add(tslnudCenterPoints);

            tsmiArrowHeadsBothSide = new ToolStripMenuItem("Arrows on both ends");
            tsmiArrowHeadsBothSide.CheckOnClick = true;
            tsmiArrowHeadsBothSide.Click       += (sender, e) =>
            {
                AnnotationOptions.ArrowHeadsBothSide = tsmiArrowHeadsBothSide.Checked;
                UpdateCurrentShape();
            };
            tsddbShapeOptions.DropDownItems.Add(tsmiArrowHeadsBothSide);

            tsmiShadow              = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_DropShadow);
            tsmiShadow.Checked      = true;
            tsmiShadow.CheckOnClick = true;
            tsmiShadow.Click       += (sender, e) =>
            {
                AnnotationOptions.Shadow = tsmiShadow.Checked;
                UpdateCurrentShape();
            };
            tsddbShapeOptions.DropDownItems.Add(tsmiShadow);

            // In dropdown menu if only last item is visible then menu opens at 0, 0 position on first open, so need to add dummy item to solve this weird bug...
            tsddbShapeOptions.DropDownItems.Add(new ToolStripSeparator()
            {
                Visible = false
            });

            #endregion Shape options

            #region Edit

            ToolStripDropDownButton tsddbEdit = new ToolStripDropDownButton(Resources.ShapeManager_CreateToolbar_Edit);
            tsddbEdit.DisplayStyle = ToolStripItemDisplayStyle.Image;
            tsddbEdit.Image        = Resources.wrench_screwdriver;
            tsMain.Items.Add(tsddbEdit);

            tsmiUndo       = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_Undo);
            tsmiUndo.Image = Resources.arrow_circle_225_left;
            tsmiUndo.ShortcutKeyDisplayString = "Ctrl+Z";
            tsmiUndo.MouseDown += (sender, e) => UndoShape();
            tsddbEdit.DropDownItems.Add(tsmiUndo);

            tsddbEdit.DropDownItems.Add(new ToolStripSeparator());

            tsmiDelete       = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_Delete);
            tsmiDelete.Image = Resources.layer__minus;
            tsmiDelete.ShortcutKeyDisplayString = "Del";
            tsmiDelete.MouseDown += (sender, e) => DeleteCurrentShape();
            tsddbEdit.DropDownItems.Add(tsmiDelete);

            tsmiDeleteAll       = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_DeleteAll);
            tsmiDeleteAll.Image = Resources.eraser;
            tsmiDeleteAll.ShortcutKeyDisplayString = "Shift+Del";
            tsmiDeleteAll.MouseDown += (sender, e) => DeleteAllShapes();
            tsddbEdit.DropDownItems.Add(tsmiDeleteAll);

            tsddbEdit.DropDownItems.Add(new ToolStripSeparator());

            tsmiMoveTop       = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_BringToFront);
            tsmiMoveTop.Image = Resources.layers_stack_arrange;
            tsmiMoveTop.ShortcutKeyDisplayString = "Home";
            tsmiMoveTop.MouseDown += (sender, e) => MoveCurrentShapeTop();
            tsddbEdit.DropDownItems.Add(tsmiMoveTop);

            tsmiMoveUp       = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_BringForward);
            tsmiMoveUp.Image = Resources.layers_arrange;
            tsmiMoveUp.ShortcutKeyDisplayString = "Page up";
            tsmiMoveUp.MouseDown += (sender, e) => MoveCurrentShapeUp();
            tsddbEdit.DropDownItems.Add(tsmiMoveUp);

            tsmiMoveDown       = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_SendBackward);
            tsmiMoveDown.Image = Resources.layers_arrange_back;
            tsmiMoveDown.ShortcutKeyDisplayString = "Page down";
            tsmiMoveDown.MouseDown += (sender, e) => MoveCurrentShapeDown();
            tsddbEdit.DropDownItems.Add(tsmiMoveDown);

            tsmiMoveBottom       = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_SendToBack);
            tsmiMoveBottom.Image = Resources.layers_stack_arrange_back;
            tsmiMoveBottom.ShortcutKeyDisplayString = "End";
            tsmiMoveBottom.MouseDown += (sender, e) => MoveCurrentShapeBottom();
            tsddbEdit.DropDownItems.Add(tsmiMoveBottom);

            #endregion Edit

            if (!form.IsEditorMode)
            {
                tsMain.Items.Add(new ToolStripSeparator());

                #region Capture

                ToolStripDropDownButton tsddbCapture = new ToolStripDropDownButton(Resources.ShapeManager_CreateContextMenu_Capture);
                tsddbCapture.DisplayStyle = ToolStripItemDisplayStyle.Image;
                tsddbCapture.Image        = Resources.camera;
                tsMain.Items.Add(tsddbCapture);

                tsmiRegionCapture       = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_CaptureRegions);
                tsmiRegionCapture.Image = Resources.layer;
                tsmiRegionCapture.ShortcutKeyDisplayString = "Enter";
                tsmiRegionCapture.MouseDown += (sender, e) =>
                {
                    form.UpdateRegionPath();
                    form.Close(RegionResult.Region);
                };
                tsddbCapture.DropDownItems.Add(tsmiRegionCapture);

                if (RegionCaptureForm.LastRegionFillPath != null)
                {
                    ToolStripMenuItem tsmiLastRegionCapture = new ToolStripMenuItem(Resources.ShapeManager_CreateToolbar_LastRegion);
                    tsmiLastRegionCapture.Image      = Resources.layers;
                    tsmiLastRegionCapture.MouseDown += (sender, e) => form.Close(RegionResult.LastRegion);
                    tsddbCapture.DropDownItems.Add(tsmiLastRegionCapture);
                }

                ToolStripMenuItem tsmiFullscreenCapture = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Capture_fullscreen);
                tsmiFullscreenCapture.Image = Resources.layer_fullscreen;
                tsmiFullscreenCapture.ShortcutKeyDisplayString = "Space";
                tsmiFullscreenCapture.MouseDown += (sender, e) => form.Close(RegionResult.Fullscreen);
                tsddbCapture.DropDownItems.Add(tsmiFullscreenCapture);

                ToolStripMenuItem tsmiActiveMonitorCapture = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Capture_active_monitor);
                tsmiActiveMonitorCapture.Image = Resources.monitor;
                tsmiActiveMonitorCapture.ShortcutKeyDisplayString = "~";
                tsmiActiveMonitorCapture.MouseDown += (sender, e) => form.Close(RegionResult.ActiveMonitor);
                tsddbCapture.DropDownItems.Add(tsmiActiveMonitorCapture);

                ToolStripMenuItem tsmiMonitorCapture = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Capture_monitor);
                tsmiMonitorCapture.HideImageMargin();
                tsmiMonitorCapture.Image = Resources.monitor_window;
                tsddbCapture.DropDownItems.Add(tsmiMonitorCapture);

                Screen[] screens = Screen.AllScreens;

                for (int i = 0; i < screens.Length; i++)
                {
                    Screen            screen = screens[i];
                    ToolStripMenuItem tsmi   = new ToolStripMenuItem($"{screen.Bounds.Width}x{screen.Bounds.Height}");
                    tsmi.ShortcutKeyDisplayString = (i + 1).ToString();
                    int index = i;
                    tsmi.MouseDown += (sender, e) =>
                    {
                        form.MonitorIndex = index;
                        form.Close(RegionResult.Monitor);
                    };
                    tsmiMonitorCapture.DropDownItems.Add(tsmi);
                }

                #endregion Capture

                #region Options

                ToolStripDropDownButton tsddbOptions = new ToolStripDropDownButton(Resources.ShapeManager_CreateContextMenu_Options);
                tsddbOptions.DisplayStyle = ToolStripItemDisplayStyle.Image;
                tsddbOptions.Image        = Resources.gear;
                tsMain.Items.Add(tsddbOptions);

                tsmiQuickCrop                          = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Multi_region_mode);
                tsmiQuickCrop.Checked                  = !Config.QuickCrop;
                tsmiQuickCrop.CheckOnClick             = true;
                tsmiQuickCrop.ShortcutKeyDisplayString = "Q";
                tsmiQuickCrop.Click                   += (sender, e) => Config.QuickCrop = !tsmiQuickCrop.Checked;
                tsddbOptions.DropDownItems.Add(tsmiQuickCrop);

                tsmiTips                          = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Show_tips);
                tsmiTips.Checked                  = Config.ShowHotkeys;
                tsmiTips.CheckOnClick             = true;
                tsmiTips.ShortcutKeyDisplayString = "F1";
                tsmiTips.Click                   += (sender, e) => Config.ShowHotkeys = tsmiTips.Checked;
                tsddbOptions.DropDownItems.Add(tsmiTips);

                ToolStripMenuItem tsmiShowInfo = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Show_position_and_size_info);
                tsmiShowInfo.Checked      = Config.ShowInfo;
                tsmiShowInfo.CheckOnClick = true;
                tsmiShowInfo.Click       += (sender, e) => Config.ShowInfo = tsmiShowInfo.Checked;
                tsddbOptions.DropDownItems.Add(tsmiShowInfo);

                ToolStripMenuItem tsmiShowMagnifier = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Show_magnifier);
                tsmiShowMagnifier.Checked      = Config.ShowMagnifier;
                tsmiShowMagnifier.CheckOnClick = true;
                tsmiShowMagnifier.Click       += (sender, e) => Config.ShowMagnifier = tsmiShowMagnifier.Checked;
                tsddbOptions.DropDownItems.Add(tsmiShowMagnifier);

                ToolStripMenuItem tsmiUseSquareMagnifier = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Square_shape_magnifier);
                tsmiUseSquareMagnifier.Checked      = Config.UseSquareMagnifier;
                tsmiUseSquareMagnifier.CheckOnClick = true;
                tsmiUseSquareMagnifier.Click       += (sender, e) => Config.UseSquareMagnifier = tsmiUseSquareMagnifier.Checked;
                tsddbOptions.DropDownItems.Add(tsmiUseSquareMagnifier);

                ToolStripLabeledNumericUpDown tslnudMagnifierPixelCount = new ToolStripLabeledNumericUpDown(Resources.ShapeManager_CreateContextMenu_Magnifier_pixel_count_);
                tslnudMagnifierPixelCount.Content.Minimum      = RegionCaptureOptions.MagnifierPixelCountMinimum;
                tslnudMagnifierPixelCount.Content.Maximum      = RegionCaptureOptions.MagnifierPixelCountMaximum;
                tslnudMagnifierPixelCount.Content.Increment    = 2;
                tslnudMagnifierPixelCount.Content.Value        = Config.MagnifierPixelCount;
                tslnudMagnifierPixelCount.Content.ValueChanged = (sender, e) => Config.MagnifierPixelCount = (int)tslnudMagnifierPixelCount.Content.Value;
                tsddbOptions.DropDownItems.Add(tslnudMagnifierPixelCount);

                ToolStripLabeledNumericUpDown tslnudMagnifierPixelSize = new ToolStripLabeledNumericUpDown(Resources.ShapeManager_CreateContextMenu_Magnifier_pixel_size_);
                tslnudMagnifierPixelSize.Content.Minimum      = RegionCaptureOptions.MagnifierPixelSizeMinimum;
                tslnudMagnifierPixelSize.Content.Maximum      = RegionCaptureOptions.MagnifierPixelSizeMaximum;
                tslnudMagnifierPixelSize.Content.Value        = Config.MagnifierPixelSize;
                tslnudMagnifierPixelSize.Content.ValueChanged = (sender, e) => Config.MagnifierPixelSize = (int)tslnudMagnifierPixelSize.Content.Value;
                tsddbOptions.DropDownItems.Add(tslnudMagnifierPixelSize);

                ToolStripMenuItem tsmiShowCrosshair = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Show_screen_wide_crosshair);
                tsmiShowCrosshair.Checked      = Config.ShowCrosshair;
                tsmiShowCrosshair.CheckOnClick = true;
                tsmiShowCrosshair.Click       += (sender, e) => Config.ShowCrosshair = tsmiShowCrosshair.Checked;
                tsddbOptions.DropDownItems.Add(tsmiShowCrosshair);

                ToolStripMenuItem tsmiEnableAnimations = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_EnableAnimations);
                tsmiEnableAnimations.Checked      = Config.EnableAnimations;
                tsmiEnableAnimations.CheckOnClick = true;
                tsmiEnableAnimations.Click       += (sender, e) => Config.EnableAnimations = tsmiEnableAnimations.Checked;
                tsddbOptions.DropDownItems.Add(tsmiEnableAnimations);

                ToolStripMenuItem tsmiFixedSize = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Fixed_size_region_mode);
                tsmiFixedSize.Checked      = Config.IsFixedSize;
                tsmiFixedSize.CheckOnClick = true;
                tsmiFixedSize.Click       += (sender, e) => Config.IsFixedSize = tsmiFixedSize.Checked;
                tsddbOptions.DropDownItems.Add(tsmiFixedSize);

                ToolStripDoubleLabeledNumericUpDown tslnudFixedSize = new ToolStripDoubleLabeledNumericUpDown(Resources.ShapeManager_CreateContextMenu_Width_,
                                                                                                              Resources.ShapeManager_CreateContextMenu_Height_);
                tslnudFixedSize.Content.Minimum      = 10;
                tslnudFixedSize.Content.Maximum      = 10000;
                tslnudFixedSize.Content.Increment    = 10;
                tslnudFixedSize.Content.Value        = Config.FixedSize.Width;
                tslnudFixedSize.Content.Value2       = Config.FixedSize.Height;
                tslnudFixedSize.Content.ValueChanged = (sender, e) => Config.FixedSize = new Size((int)tslnudFixedSize.Content.Value, (int)tslnudFixedSize.Content.Value2);
                tsddbOptions.DropDownItems.Add(tslnudFixedSize);

                ToolStripMenuItem tsmiShowFPS = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_Show_FPS);
                tsmiShowFPS.Checked      = Config.ShowFPS;
                tsmiShowFPS.CheckOnClick = true;
                tsmiShowFPS.Click       += (sender, e) => Config.ShowFPS = tsmiShowFPS.Checked;
                tsddbOptions.DropDownItems.Add(tsmiShowFPS);

                ToolStripMenuItem tsmiRememberMenuState = new ToolStripMenuItem(Resources.ShapeManager_CreateContextMenu_RememberMenuState);
                tsmiRememberMenuState.Checked      = Config.RememberMenuState;
                tsmiRememberMenuState.CheckOnClick = true;
                tsmiRememberMenuState.Click       += (sender, e) => Config.RememberMenuState = tsmiRememberMenuState.Checked;
                tsddbOptions.DropDownItems.Add(tsmiRememberMenuState);

                #endregion Options
            }

            ToolStripLabel tslDragRight = new ToolStripLabel()
            {
                Alignment    = ToolStripItemAlignment.Right,
                DisplayStyle = ToolStripItemDisplayStyle.Image,
                Image        = Resources.ui_radio_button_uncheck,
                Margin       = new Padding(0, 0, 2, 0),
                Padding      = new Padding(2)
            };

            tsMain.Items.Add(tslDragRight);

            tslDragLeft.MouseDown   += TslDrag_MouseDown;
            tslDragRight.MouseDown  += TslDrag_MouseDown;
            tslDragLeft.MouseEnter  += TslDrag_MouseEnter;
            tslDragRight.MouseEnter += TslDrag_MouseEnter;
            tslDragLeft.MouseLeave  += TslDrag_MouseLeave;
            tslDragRight.MouseLeave += TslDrag_MouseLeave;

            foreach (ToolStripItem tsi in tsMain.Items.OfType <ToolStripItem>())
            {
                if (!string.IsNullOrEmpty(tsi.Text))
                {
                    tsi.MouseEnter += (sender, e) =>
                    {
                        Point pos = CaptureHelpers.ScreenToClient(menuForm.PointToScreen(tsi.Bounds.Location));
                        pos.Y += tsi.Height + 8;

                        MenuTextAnimation.Text     = tsi.Text;
                        MenuTextAnimation.Position = pos;
                        MenuTextAnimation.Start();
                    };

                    tsi.MouseLeave += TsMain_MouseLeave;
                }
            }

            tsMain.ResumeLayout(false);
            tsMain.PerformLayout();
            menuForm.ResumeLayout(false);

            menuForm.Show(form);

            UpdateMenu();

            CurrentShapeChanged     += shape => UpdateMenu();
            CurrentShapeTypeChanged += shapeType => UpdateMenu();
            ShapeCreated            += shape => UpdateMenu();

            ConfigureMenuState();

            form.Activate();
        }
        protected override void Draw(Graphics g)
        {
            // Draw snap rectangles
            if (ShapeManager.IsCreating && ShapeManager.IsSnapResizing)
            {
                BaseShape shape = ShapeManager.CurrentShape;

                if (shape != null)
                {
                    foreach (Size size in Config.SnapSizes)
                    {
                        Rectangle snapRect = CaptureHelpers.CalculateNewRectangle(shape.StartPosition, shape.EndPosition, size);
                        g.DrawRectangleProper(markerPen, snapRect);
                    }
                }
            }

            List <BaseShape> areas = ShapeManager.ValidRegions.ToList();

            if (areas.Count > 0)
            {
                // Create graphics path from all regions
                UpdateRegionPath();

                // If background is dimmed then draw non dimmed background to region selections
                if (Config.UseDimming)
                {
                    using (Region region = new Region(regionDrawPath))
                    {
                        g.Clip = region;
                        g.FillRectangle(lightBackgroundBrush, ScreenRectangle0Based);
                        g.ResetClip();
                    }
                }

                // Blink borders of all regions slightly to make non active regions to be visible in both dark and light backgrounds
                using (Pen blinkBorderPen = new Pen(colorBlinkAnimation.GetColor()))
                {
                    g.DrawPath(blinkBorderPen, regionDrawPath);
                }
            }

            // Draw effect shapes
            foreach (BaseEffectShape effectShape in ShapeManager.EffectShapes)
            {
                effectShape.OnDraw(g);
            }

            ShapeManager.OrderStepShapes();

            // Draw drawing shapes
            foreach (BaseDrawingShape drawingShape in ShapeManager.DrawingShapes)
            {
                drawingShape.OnDraw(g);
            }

            // Draw animated rectangle on hover area
            if (ShapeManager.IsCurrentHoverAreaValid)
            {
                using (GraphicsPath hoverDrawPath = new GraphicsPath {
                    FillMode = FillMode.Winding
                })
                {
                    ShapeManager.CreateShape(ShapeManager.CurrentHoverRectangle).AddShapePath(hoverDrawPath, -1);

                    g.DrawPath(borderPen, hoverDrawPath);
                    g.DrawPath(borderDotPen, hoverDrawPath);
                }
            }

            // Draw animated rectangle on selection area
            if (ShapeManager.IsCurrentShapeTypeRegion && ShapeManager.IsCurrentRectangleValid)
            {
                g.DrawRectangleProper(borderPen, ShapeManager.CurrentRectangle);
                g.DrawRectangleProper(borderDotPen, ShapeManager.CurrentRectangle);

                if (Mode == RectangleRegionMode.Ruler)
                {
                    DrawRuler(g, ShapeManager.CurrentRectangle, borderPen, 5, 10);
                    DrawRuler(g, ShapeManager.CurrentRectangle, borderPen, 15, 100);

                    Point centerPos = new Point(ShapeManager.CurrentRectangle.X + ShapeManager.CurrentRectangle.Width / 2, ShapeManager.CurrentRectangle.Y + ShapeManager.CurrentRectangle.Height / 2);
                    int   markSize  = 10;
                    g.DrawLine(borderPen, centerPos.X, centerPos.Y - markSize, centerPos.X, centerPos.Y + markSize);
                    g.DrawLine(borderPen, centerPos.X - markSize, centerPos.Y, centerPos.X + markSize, centerPos.Y);
                }
            }

            // Draw all regions rectangle info
            if (Config.ShowInfo)
            {
                // Add hover area to list so rectangle info can be shown
                if (ShapeManager.IsCurrentShapeTypeRegion && ShapeManager.IsCurrentHoverAreaValid && areas.All(area => area.Rectangle != ShapeManager.CurrentHoverRectangle))
                {
                    BaseShape shape = ShapeManager.CreateShape(ShapeManager.CurrentHoverRectangle);
                    areas.Add(shape);
                }

                foreach (BaseShape regionInfo in areas)
                {
                    if (regionInfo.Rectangle.IsValid())
                    {
                        string areaText = GetAreaText(regionInfo.Rectangle);
                        DrawAreaText(g, areaText, regionInfo.Rectangle);
                    }
                }
            }

            // Draw resize nodes
            DrawObjects(g);

            // Draw F1 tips
            if (Config.ShowTips)
            {
                DrawTips(g);
            }

            if (Mode == RectangleRegionMode.Annotation)
            {
                if (Config.ShowMenuTip)
                {
                    // Draw right click menu tip
                    DrawMenuTip(g);
                }
                else
                {
                    // If current shape changed then draw it temporary
                    DrawCurrentShapeText(g);
                }
            }

            // Draw magnifier
            if (Config.ShowMagnifier)
            {
                DrawMagnifier(g);
            }

            // Draw screen wide crosshair
            if (Config.ShowCrosshair)
            {
                DrawCrosshair(g);
            }
        }
Beispiel #27
0
        public void ShowMenu()
        {
            ContextMenuStrip cms = new ContextMenuStrip()
            {
                Font      = new Font("Arial", 10f),
                AutoClose = false
            };

            cms.KeyUp += (sender, e) =>
            {
                if (e.KeyCode == Keys.Escape)
                {
                    cms.Close();
                }
            };

            ToolStripMenuItem tsmiContinue = new ToolStripMenuItem(Resources.QuickTaskMenu_ShowMenu_Continue);

            tsmiContinue.Image  = Resources.control;
            tsmiContinue.Click += (sender, e) =>
            {
                cms.Close();
                OnTaskInfoSelected(null);
            };
            cms.Items.Add(tsmiContinue);

            cms.Items.Add(new ToolStripSeparator());

            if (Program.Settings != null && Program.Settings.QuickTaskPresets != null && Program.Settings.QuickTaskPresets.Count > 0)
            {
                foreach (QuickTaskInfo taskInfo in Program.Settings.QuickTaskPresets)
                {
                    if (taskInfo.IsValid)
                    {
                        ToolStripMenuItem tsmi = new ToolStripMenuItem {
                            Text = taskInfo.ToString().Replace("&", "&&"), Tag = taskInfo
                        };
                        tsmi.Image  = FindSuitableIcon(taskInfo);
                        tsmi.Click += (sender, e) =>
                        {
                            QuickTaskInfo selectedTaskInfo = ((ToolStripMenuItem)sender).Tag as QuickTaskInfo;
                            cms.Close();
                            OnTaskInfoSelected(selectedTaskInfo);
                        };
                        cms.Items.Add(tsmi);
                    }
                    else
                    {
                        cms.Items.Add(new ToolStripSeparator());
                    }
                }

                cms.Items[0].Select();

                cms.Items.Add(new ToolStripSeparator());
            }

            ToolStripMenuItem tsmiEdit = new ToolStripMenuItem(Resources.QuickTaskMenu_ShowMenu_Edit_this_menu___);

            tsmiEdit.Image  = Resources.pencil;
            tsmiEdit.Click += (sender, e) =>
            {
                cms.Close();
                new QuickTaskMenuEditorForm().ShowDialog();
            };
            cms.Items.Add(tsmiEdit);

            cms.Items.Add(new ToolStripSeparator());

            ToolStripMenuItem tsmiCancel = new ToolStripMenuItem(Resources.QuickTaskMenu_ShowMenu_Cancel);

            tsmiCancel.Image  = Resources.cross;
            tsmiCancel.Click += (sender, e) => cms.Close();
            cms.Items.Add(tsmiCancel);

            if (ShareXResources.UseCustomTheme)
            {
                ShareXResources.ApplyCustomThemeToContextMenuStrip(cms);
            }

            Point cursorPosition = CaptureHelpers.GetCursorPosition();

            cursorPosition.Offset(-10, -10);
            cms.Show(cursorPosition);
            cms.Focus();
        }
Beispiel #28
0
 public void Update()
 {
     Buttons           = Control.MouseButtons;
     Position          = Control.MousePosition;
     ZeroBasedPosition = CaptureHelpers.ScreenToClient(Position);
 }
Beispiel #29
0
        private void colorTimer_Tick(object sender, EventArgs e)
        {
            Point position = CaptureHelpers.GetCursorPosition();

            UpdateColor(position.X, position.Y);
        }
        /// <summary>Captures a screenshot of a window using the Windows DWM</summary>
        /// <param name="handle">handle of the window to capture</param>
        /// <returns>the captured window image with or without cursor</returns>
        public static Image CaptureWithDWM(Workflow wfdwm, IntPtr handle)
        {
            DebugHelper.WriteLine("Capturing with DWM");
            Image  windowImageDwm = null;
            Bitmap redBGImage     = null;

            Rectangle windowRect = CaptureHelpers.GetWindowRectangle(handle);

            if (windowRect.Width == 0)
            {
                System.Threading.Thread.Sleep(250);
                windowRect = CaptureHelpers.GetWindowRectangle(handle); // try again
            }

            if (windowRect.Width > 0 && NativeMethods.IsDWMEnabled())
            {
                if (wfdwm.ActiveWindowDwmUseCustomBackground)
                {
                    windowImageDwm = CaptureWindowWithDWM(handle, windowRect, out redBGImage, wfdwm.ActiveWindowDwmBackColor);
                }
                else if (wfdwm.ActiveWindowClearBackground)
                {
                    windowImageDwm = CaptureWindowWithDWM(handle, windowRect, out redBGImage, Color.White);
                }
            }

            if (windowImageDwm == null)
            {
                DebugHelper.WriteLine("Standard capture (no transparency)");
                windowImageDwm = Screenshot.CaptureRectangleNative(windowRect);
            }

            Image result = RemoveCorners(handle, windowImageDwm, redBGImage, windowRect);

            if (result != null)
            {
                windowImageDwm = result;
            }

            if (wfdwm.ActiveWindowIncludeShadows)
            {
                // Draw shadow manually to be able to have shadows in every case
                windowImageDwm = HelpersLib.GraphicsHelper.Core.AddBorderShadow((Bitmap)windowImageDwm, true);

                if (wfdwm.DrawCursor)
                {
                    Point shadowOffset = HelpersLib.GraphicsHelper.Core.ShadowOffset;
#if DEBUG
                    DebugHelper.WriteLine("Fixed cursor position (before): " + windowRect.ToString());
#endif
                    windowRect.X -= shadowOffset.X;
                    windowRect.Y -= shadowOffset.Y;
#if DEBUG
                    DebugHelper.WriteLine("Fixed cursor position (after):  " + windowRect.ToString());
#endif
                }
            }

            if (wfdwm.DrawCursor)
            {
                CaptureHelpers.DrawCursorToImage(windowImageDwm, windowRect.Location);
            }

            return(windowImageDwm);
        }