0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

c# windowsフォームで表示した画像を右クリックで保存する(PictureBox)

Last updated at Posted at 2022-09-05

windowsフォームで表示した画像を名前付きで保存する方法
PictureBoxは、windowsフォーム上で簡単に画像を表示できる

picturebox.jpg

マウスの右クリック検知

右クリックのイベントは標準にない
マウスダウンイベントのボタンを利用する

Form1.cs
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        SavePictureBoxImage();
    }
}

ソースコード

右クリックを検知したら、保存ダイアログを開く関数を追加

Form1.cs
using System.Drawing.Imaging;

namespace WinFormsPictureBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            pictureBox.ImageLocation = @"C:\Users\xxxx\Downloads\xxxx.jpg";
            pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                SavePictureBoxImage();
            }
        }

        private void SavePictureBoxImage()
        {
            try
            {
                string filePath = pictureBox.ImageLocation;
                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException();
                }
    
                using (var sfd = new SaveFileDialog())
                {
                    sfd.FileName = Path.GetFileName(filePath);
                    sfd.Filter = "JPG|*.jpg|PNG|*.png|All files(*.*)|*.*";            
                    sfd.RestoreDirectory = true;
    
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {                
                        pictureBox.Image.Save(sfd.FileName, ImageFormat.Jpeg);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("The file not found�B", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

    }
}

Reference

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?