2025年3月18日 星期二 甲辰(龙)年 月十七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > .net

自定义不规则窗体和控件

时间:02-11来源:作者:点击数:37

自定义不规则窗体和控件

  • using System;
  • using System.Collections.Generic;
  • using System.ComponentModel;
  • using System.Data;
  • using System.Drawing;
  • using System.Linq;
  • using System.Text;
  • using System.Windows.Forms;
  • namespace WindowsFormsApplication1
  • {
  • public partial class Form1 : Form
  • {
  • /* 《自定义窗体的创建步骤》:
  • *
  • *No.1: 位图文件选用*.GIF或*.PNG格式,也就是可以保存“透明背景色”的图片格式。
  • *No.2: 将TransparencyKey属性设置为BackColor同样的颜色值。
  • *No.3: 将FormBorderStyle属性设置为None。
  • *No.4: 添加窗体常用功能:移动,关闭,标题栏等等。
  • *
  • */
  • /* 《自定义控件的创建步骤》:
  • *
  • * 1.创建一个GraphicsPath类的实例对象。
  • * 2.指定好该对象的各项细节(如大小、形状等等)。
  • * 3.将控件的Region属性设置为上面建立的GraphicsPath类的实例对象。
  • *
  • */
  • #region 恢复 窗体必要功能の相关代码
  • private Point mouse_offset; //Point表示在二维平面中定义点的、整数 X 和 Y 坐标的有序对。
  • /*【Tip】:下面相关事件的代码可以直接使用。
  • *
  • * 只要在、新建的窗体、的对应事件中选择以下事件代码即可。
  • *
  • */
  • private void Form_MouseDown(object sender , MouseEventArgs e)
  • {
  • mouse_offset = new Point(e.X , e.Y); //将当前鼠标相对于“窗体”左上角的坐标赋值给mouse_offset
  • }
  • private void Form_MouseMove(object sender , MouseEventArgs e)
  • {
  • if ( e.Button == MouseButtons.Left )
  • {
  • Point mousePos = Control.MousePosition; //将鼠标当前的"屏幕"位置坐标,赋值给mousePos变量
  • mousePos.Offset(-mouse_offset.X , -mouse_offset.Y); /* Offset的作用:将当前鼠标的Point 平移指定的量。
  • * 这里“负号”的含义是:
  • * 因为窗体左上角会向下移动到当前鼠标的位置,
  • * 为了使窗体不改变与鼠标的相对位置,而减去原来鼠标相当于窗体左上
  • * 角的位移量。这样就进入“窗体移动”状态。
  • */
  • Location = mousePos;
  • }
  • }
  • private void 关闭_Click(object sender , EventArgs e)
  • {
  • this.Close(); //实现窗体的关闭功能
  • }
  • #endregion
  • private void CustomButton_Paint(object sender,System.Windows.Forms.PaintEventArgs e)
  • {
  • //初始化一个GraphicsPath类的对象
  • System.Drawing.Drawing2D.GraphicsPath myGraphicsPath = new System.Drawing.Drawing2D.GraphicsPath();
  • ////////////////////////////////////////////
  • ////举一个例子:创建一个像文本的按钮控件////
  • ////////////////////////////////////////////
  • //确定一个“字符串”,该字符串就是控件的形状
  • string stringText = "Click Me!";
  • //确定字符串的“字体”
  • FontFamily family = new FontFamily("Arial");
  • //确定字符串的“风格 ”
  • int fontStyle = (int)FontStyle.Bold;
  • //确定字符串的“高度 ”
  • int emSize = 35;
  • //确定字符串的“起始位置”,它是从控件开始计算而非窗体
  • PointF origin = new PointF(0, 0);
  • //一个StringFormat对象来确定字符串的字间距以及“对齐方式”
  • StringFormat format = new StringFormat(StringFormat.GenericDefault);
  • //////////////////////////////////////////
  • /////////////// END //////////////////////
  • //////////////////////////////////////////
  • //用AddString方法创建字符串
  • myGraphicsPath.AddString(stringText, family, fontStyle, emSize, origin, format);
  • //将控件的Region属性设置为上面创建的GraphicsPath对象
  • CustomButton.Region = new Region(myGraphicsPath);
  • }
  • public Form1()
  • {
  • InitializeComponent();
  • }
  • }
  • }

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门