winform建立非矩形窗体

非规则窗体可能会需要加的功能代码:

1:因为没有了最上边的标题栏,所以需要加窗体鼠标拖动功能,在Form里面加如下代码:

#region   移动窗体
        // 移动窗体
        const int WM_NCLBUTTONDOWN = 0xA1;
        const int HT_CAPTION = 0x2;
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        // 窗体上鼠标按下时
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left & this.WindowState == FormWindowState.Normal)
            {
                // 移动窗体
                this.Capture = false;
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }
        #endregion

一:窗体形状为图片

1:将窗体的TransparencyKey属性设为窗体的背景色

2:将窗体的FormBorderStyle属性设为None

3:设置窗体的背景属性(BackgroundImage)为准备好的图片(图片背景需为透明,所以是png格式)

4:结果:

image

 一种简单的处理掉背景色的方法:(简单图片可用)

在ppt中插入准备好的图片,点删除背景

image

如和需求有差别 可以点选标记

image

最后保存为png即可

image

二:窗体形状为文字

法1:

1:窗体的FormBorderStyle属性设为None

2:加如下代码:

public LoginForm()
        {
            InitializeComponent();
            GraphicsPath path = new GraphicsPath();
            //这里绘画图像
            string stringText = "C#";
            FontFamily family = new FontFamily("隶书");
            int fontStyle = (int)FontStyle.Bold;//粗体
            int emSize = 250;//字体大小
            Point origin = new Point(20, 20);//起始位置
            StringFormat format = StringFormat.GenericDefault;

            path.AddString(stringText, family, fontStyle, emSize, origin, format);

            Region re = new Region(path);
            //将窗口设置为图像的形状
            this.Region = re;
        }

3:字体的颜色 控制form的背景色

4:结果如下

image

法2:

图片可由Windows画图工具中写字生成 或截图出  背景色

private void Form1_Load(object sender, EventArgs e)
{
bit = new Bitmap("font.bmp");//从指定的图像初始化Bitmap类对象//图片背景色为while
bit.MakeTransparent(Color.White);//使用默认的透明颜色对Bitmap位图透明
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawImage((Image)bit, new Point(0, 0));//在指定位置按指定大小绘制图片的指定部分
}

原文地址:https://www.cnblogs.com/happyqiang/p/5425207.html