0

So, I'm trying to make simple screenshot app in Window Forms, but i would like my button to dissapear whenever I take a shot. Unfortunately, it does not want to be invisible, even after setting Visible to false:

        {
            InitializeComponent();
            this.BackColor = Color.Red;
            this.TransparencyKey = BackColor;
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
        }

        Image tmp = Image.FromFile("C:/Users/Bartek/source/repos/Hadr/Hadr/Image/image.png");

        private void button1_Click_1(object sender, EventArgs e)
        {
            Bitmap bmp = new Bitmap(tmp.Width, tmp.Height);
            Graphics g = Graphics.FromImage(bmp);
            button1.Visible = false;
            g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
            pictureBox1.Image = bmp;
            bmp.Save("C:/Folder/image1.png",System.Drawing.Imaging.ImageFormat.Png);
        }

I have set dock on picturebox to fill, and placed button in the way showed on screen: enter image description here

I'm kindly asking for help

4
  • 2
    As a hack that you should never use, you could add a call to Application.DoEvents() after setting button1.Visible = false.
    – adv12
    Commented Jan 6, 2022 at 18:49
  • 2
    Just a guess but usually generated click events do not include _1 button1_Click_1(object sender, EventArgs e) is usually button1_Click(object sender, EventArgs e)
    – Sorceri
    Commented Jan 6, 2022 at 19:13
  • 1
    You have to exit the handler before the change to Visible will take effect. Because of that everything needed to take the screenshot should not happen in that event handler. Post a message instead, then react to that message to grab the screenshot. Commented Jan 6, 2022 at 19:33
  • 1
    Can't recreate it with the posted code. My image does not show a button.
    – LarsTech
    Commented Jan 6, 2022 at 19:44

1 Answer 1

2

Hide the button first and then use BeginInvoke() to defer making the screenshot until the system updates controls, like this:

private void button1_Click_1(object sender, EventArgs e)
{
    button1.Visible = false;
    BeginInvoke(MakeScreenShot);
}

void MakeScreenshot()
{
    Bitmap bmp = new Bitmap(tmp.Width, tmp.Height);
    Graphics g = Graphics.FromImage(bmp);
    g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
    pictureBox1.Image = bmp;
    bmp.Save("C:/Folder/image1.png", System.Drawing.Imaging.ImageFormat.Png);
    
    button1.Visible = true;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.