Tilo Jung

Tilo Jung

  • 1.6k
  • 18
  • 3.5k

transparency error

Apr 2 2024 9:57 AM

Hello, I am trying to program a transparent form with opacity that goes up during 7 seconds from 0,1 (transparent) to 1 (nontransparent).

I am using Visual Studio 2010. Without wisual studio, using csc.exe it works. But visual studio debugging gives me allways the error, on the line: this.Opacity += 0.1; that there is an Invalid cross-thread operation: The Form1 control was accessed by a thread other than the thread for which it was created.

I really want to use visual studio. So please tell me how to do it right. the code for the windows form is below:

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

namespace Opacity
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            this.timer_Tick();
        }
        private void timer_Tick()
        {
            this.aTimer = new System.Timers.Timer();
            aTimer.Interval = 175;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
            aTimer.Elapsed += new ElapsedEventHandler(OnTimeEvent);
        }
        private void OnTimeEvent(Object source, System.Timers.ElapsedEventArgs e)
        {
            if (this.Opacity == 1.0)
            {
                return;
            }
            else
            {
                this.Opacity += 0.1;
                this.Text = "Opacity = " + this.Opacity.ToString();
            }
        }
        private void InitializeComponent()
        {
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Name = "Form1";
            this.Opacity = 0.1;
            this.Text = "Opacity";
            this.TopMost = true;
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
        }
        private System.Timers.Timer aTimer;
    }
    static class Program
    {
        /// <summary>
        /// Der Haupteinstiegspunkt für die Anwendung.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

 


Answers (3)