无边框窗体及移动
一、无边框窗体
1.创建无边框窗体
将窗体FormBorderStyle属性设为None
2.无边框窗体的关闭、最小、最大化按钮可以自己添加按钮并实现功能
(1)为了视觉效果,可以添加一个pictureBox,将背景改为一张图片
(2)在这个pictureBox控件里设置鼠标移出、移出、按下、点击事件
(3)分别准备三张图片,一张作为按钮初始的背景,一张做鼠标移入,鼠标移开时再变会初始图片,再一张左鼠标按下
这里用关闭按钮举例说明:
//关闭按钮,鼠标移入后的事件 private void pictureBox1_MouseEnter(object sender, EventArgs e) { pictureBox1.Image = Image.FromFile("E:\\0425班课程\\6. winform 窗体\\winform团队项目\\diancanxitong xiangmu\\Buttons\\btn_close_highlight.png");//pictureBox控件的Name.BackgroundImage=Image.FromFile(括号里面是文件路径,注意要用双斜线); } //鼠标按下后的事件,执行按钮变色,这里是给他切换了一张图片 private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { pictureBox1.Image = Image.FromFile("E:\\0425班课程\\6. winform 窗体\\winform团队项目\\diancanxitong xiangmu\\Buttons\\btn_close_down.png"); } //鼠标移出时将变为原来的颜色,将原图片换回去 private void pictureBox1_MouseLeave(object sender, EventArgs e) { pictureBox1.Image = Image.FromFile("E:\\0425班课程\\6. winform 窗体\\winform团队项目\\diancanxitong xiangmu\\Buttons\\btn_close_disable.png"); } //鼠标点击关闭按钮时执行窗体关闭 private void pictureBox1_Click(object sender, EventArgs e) { this.Close(); }
效果展示:
鼠标移入时: 鼠标移开时: 鼠标按下时:
无边框窗体移动的方法:
//窗体移动API [DllImport("user32.dll")]//DllImport需要引用命名空间 public static extern bool ReleaseCapture(); [DllImport("user32.dll")] public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int IParam); public const int WM_SYSCOMMAND = 0x0112; public const int SC_MOVE = 0xF010; public const int HTCAPTION = 0x0002; [DllImport("user32")] private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam); private const int WM_SETREDRAW = 0xB;
private void XG_MouseDown(object sender, MouseEventArgs e)//此处是窗体事件中,鼠标按下事件private void 自己窗体的名字_MouseDown.... { if (this.WindowState == FormWindowState.Normal) { ReleaseCapture(); SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0); } }