【WinForm】WinForm常见窗体技术汇总

news/2025/2/22 9:54:10/

文章目录

  • 前言
  • 一、窗体调用外部程序与渐变窗体
    • 1、效果
    • 2、界面设计
    • 3、代码
  • 二、按回车键跳转窗体中的光标焦点
    • 1、效果
    • 2、界面设计
    • 3、代码
  • 三、剪切板操作
    • 1、效果
    • 2、界面设计
    • 3、代码
  • 四、实现拖放操作
    • 1、效果
    • 2、界面设计
    • 3、代码
  • 五、移动的窗体
    • 1、效果
    • 2、界面设计
    • 3、代码
  • 六、抓不到的窗体
    • 1、效果
    • 2、界面设计
    • 3、代码
  • 七、MDI文本编辑器窗体
    • 1、效果
    • 2、界面设计
    • 3、代码
  • 八、提示关闭窗体
    • 1、效果
    • 2、界面设计
    • 3、代码
  • 总结


前言

  • 窗体调用外部程序与渐变窗体
  • 按回车键跳转窗体中的光标焦点
  • 剪切板操作
  • 实现拖放操作
  • 移动的窗体
  • 抓不到的窗体
  • MDI窗体
  • 提示关闭窗体

一、窗体调用外部程序与渐变窗体

1、效果

窗体正在变色:
在这里插入图片描述

窗体调用网络页面–启动浏览器:
在这里插入图片描述

窗体调用本地程序–启动记事本:

在这里插入图片描述

2、界面设计

在这里插入图片描述

3、代码

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;
using System.Diagnostics;namespace 调用外部程序与渐变窗体
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){this.timer1.Enabled = true;this.Opacity = 0;}private void timer1_Tick(object sender, EventArgs e){if (this.Opacity < 1){this.Opacity += 0.05;}else{this.timer1.Enabled = false;}}private void button1_Click(object sender, EventArgs e){try{Process proc = new Process();proc.StartInfo.FileName = "notepad.exe";//注意路径proc.StartInfo.Arguments = "";//运行参数proc.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;//启动窗口状态proc.Start();}catch (Exception ex){MessageBox.Show(ex.Message, "注意", MessageBoxButtons.OK, MessageBoxIcon.Information);}}private void button2_Click(object sender, EventArgs e){try{Process proc = new Process();Process.Start("IExplore.exe", "http://www.baidu.com");}catch (Exception ex){MessageBox.Show(ex.Message, "注意", MessageBoxButtons.OK, MessageBoxIcon.Information);}}private void button3_Click(object sender, EventArgs e){try{Process proc = new Process();proc.StartInfo.FileName = @"E:\娱乐工具\qq2012\Bin\QQProtect\Bin\QQProtect";proc.Start();}catch (Exception ex){MessageBox.Show(ex.Message, "注意", MessageBoxButtons.OK, MessageBoxIcon.Information);}}}
}

二、按回车键跳转窗体中的光标焦点

1、效果

按下enter键,光标会向下移动:
在这里插入图片描述

2、界面设计

在这里插入图片描述

3、代码

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 回车跳转控件焦点
{public partial class Form1 : Form{public Form1(){InitializeComponent();}//private void txtName_KeyDown(object sender, KeyEventArgs e)//{//    if (e.KeyCode == Keys.Enter)//    {//        txtAge.Focus();//    }//}//private void txtAge_KeyDown(object sender, KeyEventArgs e)//{//    if (e.KeyValue == 13)//    {//        txtAge.Focus();//    }//}private void EnterToTab(object sender, KeyEventArgs e){if (e.KeyValue == 13){SendKeys.Send("{TAB}");     //等同于按Tab键}}}
}

三、剪切板操作

1、效果

第一个text中输入内容并选中,点击粘贴就粘贴到第二个text;
下方是图片的复制粘贴,方法一样。
在这里插入图片描述

2、界面设计

在这里插入图片描述

3、代码

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 剪切板操作
{public partial class Form1 : Form{public Form1(){InitializeComponent();}/// <summary>/// 剪切/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button1_Click(object sender, EventArgs e){if (!textBox1.SelectedText.Equals(""))Clipboard.SetText(textBox1.SelectedText);elseMessageBox.Show("未选中文本!");}/// <summary>/// 粘贴/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button2_Click(object sender, EventArgs e){if (Clipboard.ContainsText())textBox2.Text = Clipboard.GetText();elseMessageBox.Show("剪切板没有文本!");}/// <summary>/// 图片剪切/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button3_Click(object sender, EventArgs e){openFileDialog1.FileName = "";openFileDialog1.Filter = "jpg文件(*.jpg)|*.jpg|bmp文件(*.bmp)|*.bmp";if (openFileDialog1.ShowDialog() == DialogResult.OK){pictureBox1.Image = new Bitmap(openFileDialog1.FileName);Clipboard.SetImage(pictureBox1.Image);}}/// <summary>/// 图片粘贴/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void button4_Click(object sender, EventArgs e){if (Clipboard.ContainsImage()){pictureBox2.Image = Clipboard.GetImage();}}}
}

四、实现拖放操作

1、效果

可以将listview中的节点项鼠标拖动到text中。
在这里插入图片描述

2、界面设计

在这里插入图片描述

3、代码

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 实现拖放操作
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void lvSource_ItemDrag(object sender, ItemDragEventArgs e){lvSource.DoDragDrop(e.Item, DragDropEffects.Copy);}private void txtMessage_DragEnter(object sender, DragEventArgs e){e.Effect = DragDropEffects.Copy;}private void txtMessage_DragDrop(object sender, DragEventArgs e){ListViewItem lvi = (ListViewItem)e.Data.GetData(typeof(ListViewItem));txtMessage.Text = lvi.Text;lvSource.Items.Remove(lvi);}}
}

五、移动的窗体

1、效果

窗体运行之后自动移动。
在这里插入图片描述

2、界面设计

在这里插入图片描述

3、代码

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 个性化窗体界面
{public partial class Form1 : Form{public Form1(){InitializeComponent();}public int x=0;public int y=300;public bool panDuan = false;private void timer1_Tick(object sender, EventArgs e){if (x == 1366)x = 0;this.Location = new Point(x, y);x += 1;}private void Form1_MouseEnter(object sender, EventArgs e){timer1.Stop();}private void Form1_MouseLeave(object sender, EventArgs e){if(!panDuan)timer1.Start();}private void tsmiExit_Click(object sender, EventArgs e){this.Close();}private void contextMenuStrip1_Opened(object sender, EventArgs e){panDuan = true;}private void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e){panDuan = false;}private void Form1_Load(object sender, EventArgs e){this.toolTip1.ToolTipTitle = "嘿嘿";this.toolTip1.SetToolTip(this, "看徒弟的憨样!");}}
}

六、抓不到的窗体

1、效果

此窗体中放入了一张图片,在飘啊飘,抓不到。
在这里插入图片描述

2、界面设计

在这里插入图片描述

3、代码

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 抓不到的窗体
{public partial class Form1 : Form{public Form1(){InitializeComponent();}int x, y;int count = 0;Random rd = new Random();private void Form1_Load(object sender, EventArgs e){this.toolTip1.ToolTipTitle = "嘿嘿";this.toolTip1.SetToolTip(this.pictureBox1, "人品不错,给你抓到了!点击退出!");this.timer1.Enabled = true;this.Opacity = 0;}private void pictureBox1_Click(object sender, EventArgs e){this.Close();}private void pictureBox1_MouseEnter(object sender, EventArgs e){if (count == 10)MessageBox.Show("已经抓了" + count + "次了,可还是没抓到!", "哈哈", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);if (count == 20)MessageBox.Show("已经抓了" + count + "次了,是否继续?", "真佩服的坚持", MessageBoxButtons.OK, MessageBoxIcon.Question);if (count == 30){if ((MessageBox.Show("已经抓了" + count + "次了,”倔驴“这个称号,就赠与你了!", "无语了", MessageBoxButtons.OK, MessageBoxIcon.Warning)) == DialogResult.OK){if ((MessageBox.Show("的人品已经降为负的了!", "注意", MessageBoxButtons.OK, MessageBoxIcon.Warning)) == DialogResult.OK)this.Close();}}this.Opacity = 0;this.timer1.Enabled = true;x = rd.Next(0, 1300);y = rd.Next(0, 700);this.Location = new Point(x, y);count++;}private void timer1_Tick(object sender, EventArgs e){if (this.Opacity < 1){this.Opacity += 0.07;}else{this.timer1.Enabled = false;}}}
}

七、MDI文本编辑器窗体

1、效果

功能更强大的文本编辑器。
在这里插入图片描述

2、界面设计

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

3、代码

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 MDINotepad
{public partial class MainForm : Form{public MainForm(){InitializeComponent();}private void tsmiNewTxt_Click(object sender, EventArgs e){NotepadForm childForm = new NotepadForm();childForm.Text = "新建文本文档.txt";childForm.MdiParent = this;childForm.Show();}private void tsmiNewRtf_Click(object sender, EventArgs e){NotepadForm childForm = new NotepadForm();childForm.Text = "新建富文本文档.rtf";childForm.MdiParent = this;childForm.Show();}private void tsmiOpenFile_Click(object sender, EventArgs e){OpenFileDialog ofd = new OpenFileDialog();ofd.Filter = "富文本文档(*.rtf)|*.rtf|文本文档(*.txt)|*.txt";if (ofd.ShowDialog() == DialogResult.OK){NotepadForm childForm = new NotepadForm(ofd.FileName);childForm.MdiParent = this;childForm.Show();}}private void tsmiExit_Click(object sender, EventArgs e){Close();}private void tsmiHorizontalLayout_Click(object sender, EventArgs e){LayoutMdi(MdiLayout.TileHorizontal);}private void tsmiVerticalLayout_Click(object sender, EventArgs e){LayoutMdi(MdiLayout.TileVertical);}private void tsmiCascadeLayout_Click(object sender, EventArgs e){LayoutMdi(MdiLayout.Cascade);}private void tsmiMinimize_Click(object sender, EventArgs e){foreach (Form childForm in MdiChildren){childForm.WindowState = FormWindowState.Minimized;}}private void tsmiMaximize_Click(object sender, EventArgs e){foreach (Form childForm in MdiChildren){childForm.WindowState = FormWindowState.Maximized;}}private void tsmiAbout_Click(object sender, EventArgs e){AboutForm af = new AboutForm();af.ShowDialog(this);}}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;namespace MDINotepad
{public partial class AboutForm : Form{public AboutForm(){InitializeComponent();}}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;namespace MDINotepad
{public partial class NotepadForm : Form{private int _currentCharIndex;#region Code segment for constructors.public NotepadForm(){InitializeComponent();}public NotepadForm(string filePath): this(){//判断文件的后缀名,不同的文件类型使用不同的参数打开。if (filePath.EndsWith(".rtf", true, null))rtbEditor.LoadFile(filePath,RichTextBoxStreamType.RichText);elsertbEditor.LoadFile(filePath,RichTextBoxStreamType.PlainText);Text = filePath;}#endregion#region Code segment for private operations.private void Save(string filePath){try{//判断文件的后缀名,不同的文件类型使用不同的参数保存。if (filePath.EndsWith(".rtf", true, null))rtbEditor.SaveFile(filePath,RichTextBoxStreamType.RichText);elsertbEditor.SaveFile(filePath,RichTextBoxStreamType.PlainText);}catch (Exception ex){MessageBox.Show(ex.ToString());}}private void SaveAs(){sfdDemo.FilterIndex = Text.EndsWith(".rtf", true, null) ? 1 : 2;if (sfdDemo.ShowDialog() == DialogResult.OK){Save(sfdDemo.FileName);Text = sfdDemo.FileName;}}#endregion#region Code segment for event handlers.private void tsmiSaveFile_Click(object sender, EventArgs e){if (!System.IO.File.Exists(Text))SaveAs();elseSave(Text);}private void tsmiSaveAs_Click(object sender, EventArgs e){SaveAs();}private void tsmiBackColor_Click(object sender, EventArgs e){cdDemo.Color = rtbEditor.SelectionBackColor;if (cdDemo.ShowDialog() == DialogResult.OK){rtbEditor.SelectionBackColor = cdDemo.Color;}}private void rtbEditor_SelectionChanged(object sender, EventArgs e){if (rtbEditor.SelectionLength == 0){tsmiBackColor.Enabled = false;tsmiFont.Enabled = false;}else{tsmiBackColor.Enabled = true;tsmiFont.Enabled = true;}}private void tsmiFont_Click(object sender, EventArgs e){fdDemo.Color = rtbEditor.SelectionColor;fdDemo.Font = rtbEditor.SelectionFont;if (fdDemo.ShowDialog() == DialogResult.OK){rtbEditor.SelectionColor = fdDemo.Color;rtbEditor.SelectionFont = fdDemo.Font;}}private void pdEditor_PrintPage(object sender,System.Drawing.Printing.PrintPageEventArgs e){//存放当前已经处理的高度float allHeight = 0;//存放当前已经处理的宽度float allWidth = 0;//存放当前行的高度float lineHeight = 0;//存放当前行的宽度float lineWidth = e.MarginBounds.Right - e.MarginBounds.Left;//当前页没有显示满且文件没有打印完,进行循环while (allHeight < e.MarginBounds.Height&& _currentCharIndex < rtbEditor.Text.Length){//选择一个字符rtbEditor.Select(_currentCharIndex, 1);//获取选中的字体Font currentFont = rtbEditor.SelectionFont;//获取文字的尺寸SizeF currentTextSize =e.Graphics.MeasureString(rtbEditor.SelectedText, currentFont);//获取的文字宽度,对于字母间隙可以小一些,//对于空格间隙可以大些,对于汉字间隙适当调整。if (rtbEditor.SelectedText[0] == ' ')currentTextSize.Width = currentTextSize.Width * 1.5f;else if (rtbEditor.SelectedText[0] < 255)currentTextSize.Width = currentTextSize.Width * 0.6f;elsecurrentTextSize.Width = currentTextSize.Width * 0.75f;//初始位置修正2个像素,进行背景色填充e.Graphics.FillRectangle(new SolidBrush(rtbEditor.SelectionBackColor),e.MarginBounds.Left + allWidth + 2, e.MarginBounds.Top + allHeight, currentTextSize.Width, currentTextSize.Height);//使用指定颜色和字体画出当前字符e.Graphics.DrawString(rtbEditor.SelectedText, currentFont, new SolidBrush(rtbEditor.SelectionColor), e.MarginBounds.Left + allWidth, e.MarginBounds.Top + allHeight);allWidth += currentTextSize.Width;//获取最大字体高度作为行高if (lineHeight < currentFont.Height)lineHeight = currentFont.Height;//是换行符或当前行已满,allHeight加上当前行高度,//allWidth和lineHeight都设为0。if (rtbEditor.SelectedText == "\n"|| e.MarginBounds.Right - e.MarginBounds.Left < allWidth){allHeight += lineHeight;allWidth = 0;lineHeight = 0;}//继续下一个字符_currentCharIndex++;}//后面还有内容,则还有下一页if (_currentCharIndex < rtbEditor.Text.Length)e.HasMorePages = true;elsee.HasMorePages = false;}private void tsmiPrint_Click(object sender, EventArgs e){if (pdDemo.ShowDialog() == DialogResult.OK){//用户确定了打印机和设置后,进行打印。pdEditor.Print();}}private void tsmiPageSetup_Click(object sender, EventArgs e){psdDemo.ShowDialog();}private void tsmiPrintPreview_Click(object sender, EventArgs e){ppdDemo.ShowDialog();}private void pdEditor_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e){_currentCharIndex = 0;}#endregion}
}

八、提示关闭窗体

1、效果

在这里插入图片描述

2、界面设计

在这里插入图片描述

3、代码

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 提示关闭窗口
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){Application.Exit();}private void Form1_FormClosing(object sender, FormClosingEventArgs e){DialogResult choice = MessageBox.Show("确定要关闭窗体吗?", "注意", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);if (choice == DialogResult.Cancel)   //判断是否单击“取消按钮”{e.Cancel = true;}}public class MessageFilter : System.Windows.Forms.IMessageFilter     //禁止窗体拖动的类,继承自System.Windows.Forms.IMessageFilter 接口{const int WM_NCLBUTTONDOWN = 0x00A1;const int HTCAPTION = 2;public bool PreFilterMessage(ref System.Windows.Forms.Message m){if (m.Msg == WM_NCLBUTTONDOWN && m.WParam.ToInt32() == HTCAPTION)return true;return false;}}}
}

总结


http://www.ppmy.cn/news/275835.html

相关文章

30、js - Promise

一、Promise的3种状态: 1、作用&#xff1a;了解Promise对象如何关联的处理函数&#xff0c;以及代码执行顺序 2、一个Promise对象&#xff0c;必然处于以下几个状态之一&#xff1a; pending&#xff1a;初始状态&#xff0c;页面一旦调用Promise对象&#xff0c;Promise对象就…

【Docker安装部署Neo4j保姆级教程】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

PointPillar 3D目标检测模型详解

一、参考资料 pointpillars 论文 pointpillars 论文 PointPillars - gitbook_docs 使用 NVIDIA CUDA-Pointpillars 检测点云中的对象 3D点云 (Lidar)检测入门篇 - PointPillars PyTorch实现 模型部署入门教程&#xff08;三&#xff09;&#xff1a;PyTorch 转 ONNX 详解 Poin…

『Nvidia Jetson AGX Xavier笔记』Xavier(arrch64架构)搭建second点云目标检测环境!

Xavier(基于arrch64架构)搭建second点云目标检测环境&#xff01; 文章目录 一. 事先准备工作1.1. 安装cmake1.2. 创建second虚拟环境1.3. 安装一些依赖包 二. 安装pytorch以及spconv2.1. 安装pytorch以及torchvision2.2. 安装spconv2.3. 安装apex 三. second网络验证性能3.1.…

EVO安装与问题解决

1.安装方法 1.1 快捷安装 &#xff0c;直接安装最新的稳定发行版&#xff1a; pip install evo --upgrade --no-binary evo1.2 源码安装 &#xff0c;下载源码进行安装&#xff1a; 首先在任意文件夹下下载evo&#xff0c;也可以在home中直接下载 git clone https://github.…

关于SSD的一些日记

我的第一块SSD 2016年&#xff1a;SanDisk 240GB SSD Plus&#xff0c; SATA3.0 某东自营 在那时这个SSD算是非常新的SSD&#xff0c;用的技术也相当先进&#xff0c;而且网上好评如潮。在舍友三天两头的怂恿下我忍饥挨饿终于花400大洋买了个 回来做系统盘。 若问我有什么提升…

代码阅读 :SECOND pytorch版本

代码量很大。。。 框架 second.pytorch --------|---images|---second ----|---apex|---torchplus |---builder|---configs|---core|---data|---framework|---kittiviewer|---protos|---pytorch ------|---builder|---spconv |---core|---utils |---models|-…

传统工业制造企业如何实现数字化转型?

传统工业制造企业如何实现数字化转型&#xff0c;以数字驱动、实现高价值管理&#xff1f; 传统企业实现数字化转型是一条很漫长但不得不走的道路&#xff0c;看到这个问题下有很多专业人士对传统企业如何做数字化转型都提出了专业的见解&#xff0c;所以这篇就以传统制造业为…