【C#】画面の領域をマウスで範囲指定する

C#

C#でデスクトップ上の領域をマウスで選択するソースコードを記載します。

実行すると半透明のフォームを画面一杯に表示し、

マウスをドラッグすると選択した座標を取得できます。

選択領域は赤枠で追従します。

■DialosRegionSelection.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SCSupportTool
{

    public partial class DialogRegionSelection : Form
    {
        private Point startPos;
        private Point endPos;
        private bool isSelecting;
        private int reservePaint = 0;

        public DialogRegionSelection(Screen screen)
        {
            InitializeComponent();

            this.Screen = screen;
            this.FormBorderStyle = FormBorderStyle.None;
            //this.BackColor = Color.FromArgb(128, Color.Black);
            this.BackColor = Color.LightGray;
            this.Opacity = 0.5;
            this.StartPosition = FormStartPosition.Manual;
            this.Bounds = this.Screen.Bounds;
            this.ShowInTaskbar = false;
            this.TopMost = true;
            this.MouseDown += OverlayForm_MouseDown;
            this.MouseMove += OverlayForm_MouseMove;
            this.MouseUp += OverlayForm_MouseUp;
            this.Paint += OverlayForm_Paint;
        }

        public Screen Screen { get; set; }
        public Rectangle SelectedRegion { get; set; }
        public Rectangle ScreenRegion { get { return this.RectangleToScreen(this.SelectedRegion); } }

        private void DialogRegionSelection_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
        }

        private void OverlayForm_MouseDown(object sender, MouseEventArgs e)
        {
            isSelecting = true;
            this.startPos = e.Location;
            SelectedRegion = new Rectangle(e.Location, new Size());
        }

        private void OverlayForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (isSelecting)
            {
                this.endPos = e.Location;

                //selectedRegion = new Rectangle(selectedRegion.Location, new Size(e.X - selectedRegion.Left, e.Y - selectedRegion.Top));

                int x1 = this.startPos.X;
                int x2 = this.endPos.X;
                int y1 = this.startPos.Y;
                int y2 = this.endPos.Y;
                SelectedRegion = Rectangle.FromLTRB(Math.Min(x1, x2), Math.Min(y1, y2), Math.Max(x1, x2), Math.Max(y1, y2));

                this.reservePaint++;
            }
        }

        private void OverlayForm_MouseUp(object sender, MouseEventArgs e)
        {
            isSelecting = false;
            // ユーザーが領域選択を完了した場合の処理をここに追加します
            // selectedRegion 変数に選択された領域の情報が格納されています
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void OverlayForm_Paint(object sender, PaintEventArgs e)
        {
            if (isSelecting)
            {
                //using (var brush = new SolidBrush(Color.FromArgb(128, Color.Blue)))
                //{
                //    e.Graphics.FillRectangle(brush, this.ClientRectangle);
                //}
                using (var pen = new Pen(Color.Red, 2))
                {
                    e.Graphics.DrawRectangle(pen, SelectedRegion);
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.reservePaint > 0)
            {
                this.reservePaint = 0;
                this.Invalidate();
            }
        }

    }
}

■DialogRegionSelection.Designer.cs

namespace SCSupportTool
{
    partial class DialogRegionSelection
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            // 
            // timer1
            // 
            this.timer1.Enabled = true;
            this.timer1.Interval = 50;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // DialogRegionSelection
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.KeyPreview = true;
            this.Name = "DialogRegionSelection";
            this.Text = "DialogRegionSelection";
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.DialogRegionSelection_KeyDown);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Timer timer1;
    }
}

■使い方


        private List<DialogRegionSelection> dlgRegionSelectionList = new List<DialogRegionSelection>();

        private void buttonSelectRegion_Click(object sender, EventArgs e)
        {

            Screen[] screens = Screen.AllScreens;
            foreach (var screen in screens)
            {
                DialogRegionSelection dlg = new DialogRegionSelection(screen);
                dlg.FormClosed += RegionSelection_DialogClosed;
                dlg.Show(this);
                this.dlgRegionSelectionList.Add(dlg);
            }

        }

        private void RegionSelection_DialogClosed(object sender, FormClosedEventArgs e)
        {
            DialogRegionSelection dlg = (DialogRegionSelection)sender;
            if (dlg.DialogResult != DialogResult.OK)
            {
                return;
            }
            
            Rectangle screenRegion = dlg.ScreenRegion; //選択された領域をRectangleで受け取れる

            foreach (var d in this.dlgRegionSelectionList)
            {
                if (d.IsDisposed == false && d.Disposing == false)
                {
                    d.Dispose();
                }
            }
            this.dlgRegionSelectionList.Clear();

        }

以上!

コメント

タイトルとURLをコピーしました