Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a right click menu item to a picture box

When I right-click on a picturebox, by using context menu items I am showing a menu item saveImageAs.

Problem: When I right click on the picture box, it shows saveImageAs, when I click saveImageAs it will hit

private void saveImageAsToolStripMenuItem_Click(object sender, EventArgs e)
{
    //what should i use instead of click to hit form_Mouseclick

    pictureBox1.Click += form_MouseClick;
    pictureBox2.Click += form_MouseClick;
}

Here what should I use instead of pictureBox1_click() to hit form_MouseClick(). If anyone could help I would be most grateful.

private void saveImageAsToolStripMenuItem_Click(object sender, EventArgs e)
{
    pictureBox1.Click += form_MouseClick;
    pictureBox2.Click += form_MouseClick;    
} 

private void form_MouseClick(object sender, MouseEventArgs e)
{
    PictureBox pb = sender as PictureBox;
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Images|*.png;*.bmp;*.jpg";
    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        string filepath = System.IO.Path.GetExtension(sfd.FileName);
    }
    if(pb != null && sfd.FileName != null)
    {
        Image im = pb.Image;
        SaveImage(im, sfd.FileName);
    }
}

private static void SaveImage(Image im, string destPath)
{
    im.Save(destPath, System.Drawing.Imaging.ImageFormat.Png);
}
like image 318
Nag Arjun Reddy Avatar asked Sep 13 '25 22:09

Nag Arjun Reddy


1 Answers

Give it a shot!

using Module = System.Windows.Forms;

public Form1()
{
    var menu = new Module.ContextMenuStrip();

    {
        var submenu = new Module.ToolStripMenuItem();

        submenu.Text = "Sub-menu 1";

        var item = new Module.ToolStripMenuItem();

        item.Text = "Sub-item 1";
        item.MouseUp += (object sender,MouseEventArgs e) =>
        {
            // Todo
        };
        submenu.DropDownItems.Add( item );

        item = new Module.ToolStripMenuItem();
        item.Text = "Sub-item 2";
        submenu.DropDownItems.Add( item );

        menu.Items.Add( submenu );
    }

    pictureBox1.ContextMenuStrip = menu;
}
like image 106
ToyAuthor X Avatar answered Sep 15 '25 14:09

ToyAuthor X