C# winform获取窗体工作区宽度高度

这篇博客记录了一段C# WinForm应用的代码,主要展示了如何在窗体的Paint事件中利用ClientRectangle属性动态绘制多个红色和蓝色的矩形。代码通过调整百分比来改变矩形的位置,同时还处理了窗体闪烁的问题,提高了用户体验。
摘要由CSDN通过智能技术生成

获取代码如下

this.ClientRectangle.Width, 
this.ClientRectangle.Height

例程详细代码

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

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

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            Pen pen = new Pen(Color.FromArgb(255, 0, 0), 30);
            pen.Color = Color.Red;
            //g.DrawLine(pen, 10, 10, this.Width - 150, this. Height - 150);
            //g.DrawRectangle
            //int windowBorder = (this.Width - this.ClientRectangle.Width) / 2;
            //Rectangle rf = new Rectangle(10, 10, this.Width-50, this.Height - 50);
            Rectangle rf = new Rectangle(0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height);
            
            for ( int i = 0; i < 80; i+=10 )
            {
                //pen.Color = Color.FromArgb(i*5, 0, 0);

                g.DrawRectangle(pen, RectREF(rf, (float)i));

            }
            //g.DrawRectangle(pen, RectREF(rf, 10f));
            pen.Color = Color.Blue;
            g.DrawRectangle(pen, rf);
        }

        private Rectangle RectREF(Rectangle InRect, float per)
        {
            //RectangleF OutRet;
            //var Left = InRect.Left + (InRect.Width - InRect.Left) * per/100f;
            //var Top = InRect.Top + (InRect.Height - InRect.Top) * per / 100f;
            //var Width = InRect.Width * (1-per / 100f)-Left;
            //var Height = InRect.Height * (1-per / 100f)-Top;
            var Left = InRect.Left + (InRect.Width) * per / 100f;
            var Top = InRect.Top + (InRect.Height) * per / 100f;
            var Width = InRect.Width * (1 - 2 * per / 100f);// - Left;
            var Height = InRect.Height * (1 - 2 * per / 100f);// -Top;

            return new Rectangle((int)Left, (int)Top, (int)Width, (int)Height);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            //处理闪烁问题
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
        }
    }
}

运行结果如下图

参考链接

(25条消息) C# winform 获取标题栏,状态栏,菜单栏的高度_huangwenhua5000的博客-CSDN博客_c# 句柄 标题栏高度

特此记录

anlog

2022年12月24日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值