Skip to main content
 首页 » 编程设计

c#之我可以在透明的 WinForm 上绘制面板吗

2024年02月13日10JustinYoung

在看到绘制到桌面上非常困惑之后,我决定只是研究一下。我发现很多人建议创建一个与屏幕大小相同的透明 WinForm,然后在上面敲击一个面板并使用它来绘制图形。所以我对其进行了测试,但遇到了很多错误。起初,我的第二个窗体 (Form2) 不会显示,所以我不得不将它放入另一个线程并将 Form2.ShowDialog(); 放在那个线程上。在我解决了这个问题之后,我实际上吸引了面板。现在我的表单永远不会显示,但我可以看到它在我的任务栏上运行。每次我试图让它成为焦点窗口时,它永远不会工作,每当我将鼠标悬停在任务上时,我都可以看到正在创建的图形。我的问题是,是否可以在透明的 WinForm 上绘制面板并使其可见?这是我使用的代码,它主要用于查找错误(绘制状态和内容)。

void Draw() 
    { 
        while (true) 
        { 
            SolidBrush redpen = new SolidBrush(Color.Red); 
            Font font = new Font("Arial", 16); 
            PointF point = new PointF(700, 150); 
            Graphics g = panel1.CreateGraphics(); 
 
            g.DrawString(Main.state.ToString(), font, redpen, point); 
 
            Main.beginTime.Stop(); 
            Main.TimeRan = Main.beginTime.Elapsed; 
 
            string amountOfTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", Main.TimeRan.Hours, Main.TimeRan.Minutes, Main.TimeRan.Seconds, Main.TimeRan.Milliseconds / 10); 
            point = new PointF(700, 200); 
 
            g.DrawString(amountOfTime, font, redpen, point); 
 
            Thread.Sleep(10); 
            panel1.Refresh(); 
        } 
    } 
 
    private void Form2_Shown(object sender, EventArgs e) 
    { 
        Draw(); 
    } 

我主课的某个地方

    // In a method 
    Thread F2T = new Thread(FormHandlers); 
    F2T.Start(); 
 
    private void FormHandlers() 
    { 
        Form2 Form2 = new Form2(); 
        Form2.Opacity = 0.00; 
        Form2.ShowDialog(); 
    } 

编辑:经过一些测试,我注意到随着不透明度的降低,字母的不透明度也降低了,我能否做到面板透明但我正在绘制以在其中绘制的字符串不是透明的?

请您参考如下方法:

我猜您想在透明的子窗体上绘制一条消息?如果是这样,我想你可以这样做:因为 form.Opacity =0.00 使其中的所有控件都是透明的,所以我们看不到任何东西。另一种方法是,我们使用 form.TransparencyKey 来获取它。代码如下:

public Form2() 
    { 
        InitializeComponent(); 
        //hide the border of form 
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; 
        this.BackColor = Color.White; 
        //set the TransparencyKey the same as the back color 
        this.TransparencyKey = this.BackColor; 
    } 
 
protected override void OnPaint(PaintEventArgs e) 
    { 
        SolidBrush redpen = new SolidBrush(Color.Red); 
        Font font = new Font("Arial", 16); 
        PointF point = new PointF(400, 150); 
        Graphics g = e.Graphics; 
        string state = "running"; 
        g.DrawString(state, font, redpen, point); 
        string amountOfTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", 1, 2, 3, 11111 / 10); 
        PointF point2 = new PointF(500, 150); 
        g.DrawString(amountOfTime, font, redpen, point2); 
 
        //base.OnPaint(e); 
    } 

顺便说一句,你想在子窗体中显示消息,我不喜欢使用多线程,你只需在 Show() 中而不是在 ShowDialog 中调用 Form2 (),并设置Form2.TopMost=True,这样就可以操作主窗体了。尝试一下。 我的结果如下: