WinFormsでPictureBox上のマウス座標を取得するサンプルコード

東都名所 道潅山 コンピュータ
東都名所 道灌山

マウスカーソルの座標を取得します。

ソースコード

ファイル名:MouseOnImageXYWinForms.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <UseWindowsForms>true</UseWindowsForms>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>

ファイル名:Form1.cs


namespace MouseOnImageXYWinForms;

public partial class Form1 : Form
{
    private string _baseTitle;
    PictureBox pictureBox1 = new()
    {
        Dock = DockStyle.Fill,
    };

    public Form1()
    {
        InitializeComponent();
        _baseTitle = this.Text;

        // 画像読み込み
        try
        {
            pictureBox1.Image = Image.FromFile(@"C:\Users\karet\Pictures\color-sampl2.png");  // 適宜パスを変更
        }
        catch (Exception ex)
        {
            MessageBox.Show("画像読み込みエラー: " + ex.Message);
        }

        // 表示モード:画像の実ピクセルサイズで表示したい場合は Normal/AutoSize
        pictureBox1.SizeMode = PictureBoxSizeMode.Normal;

        // イベント登録
        pictureBox1.MouseMove += PictureBox1_MouseMove;
        pictureBox1.MouseLeave += PictureBox1_MouseLeave;

        this.Controls.Add(pictureBox1);
    }

    private void PictureBox1_MouseMove(object? sender, MouseEventArgs e)
    {
        if (pictureBox1.Image == null) return;

        // 画像の実ピクセル幅・高さ
        int imgWidth = pictureBox1.Image.Width;
        int imgHeight = pictureBox1.Image.Height;

        // PictureBox 内での表示サイズ
        int displayWidth = pictureBox1.ClientSize.Width;
        int displayHeight = pictureBox1.ClientSize.Height;

        // マウス位置(PictureBox 内のクライアント座標)
        int x = e.X;
        int y = e.Y;

        // 座標をクランプ
        x = Math.Max(0, Math.Min(x, imgWidth - 1));
        y = Math.Max(0, Math.Min(y, imgHeight - 1));

        this.Text = $"{_baseTitle}  |  ({x}, {y}) px  [{imgWidth}×{imgHeight} px]";

    }

    private void PictureBox1_MouseLeave(object? sender, EventArgs e)
    {
        this.Text = _baseTitle;
    }
}

動作イメージ

コメント