zoukankan      html  css  js  c++  java
  • C# 自定义控件制作和使用实例

    C# 自定义用户控件
    xiongxuanwen
     
    上篇:控件制作
     
    本例是制作一个简单的自定义控件,然后用一个简单的测试程序,对于初学者来说,本例子比较简单,只能起到抛石引玉的效果。
    我也是在学习当中,今后会将自己所学的逐步写出来和大家交流共享。
     
    第一步:新建一个控件库项目:myControl
     
    第二步:从工具箱里面拖动1个PictureBox、1个Button、6个Lable控件到用户界面上,布局如下:
           如上图,设置pictureBox的Name为picBox,背景为白色,Button的Name为btnOpen,另外靠左的三个Lable的Text属性分别为:文件名称,文件大小,文件尺寸,靠右的三个Lable的Name分别为:lblName, lblLength, lblSize.
     
    第三步:添加处理程序代码
    在btnOpen的Click事件写入代码,打开一个打开文件对话框,选择一个图形文件,打开并将它显示在picBox上。
     
    private void btnOpen_Click(object sender, EventArgs e)
    {
    OpenFileDialog ofdPic = new OpenFileDialog();
    ofdPic.Filter = "JPG(*.JPG;*.JPEG);gif文件(*.GIF)|*.jpg;*.jpeg;*.gif";
    ofdPic.FilterIndex = 1;
    ofdPic.RestoreDirectory = true;
    ofdPic.FileName = "";
    if (ofdPic.ShowDialog() == DialogResult.OK)
    {
    string sPicPaht = ofdPic.FileName.ToString();
    FileInfo fiPicInfo = new FileInfo(sPicPaht);
    long lPicLong = fiPicInfo.Length / 1024;
    string sPicName = fiPicInfo.Name;
    string sPicDirectory = fiPicInfo.Directory.ToString();
    string sPicDirectoryPath = fiPicInfo.DirectoryName;
    Bitmap bmPic = new Bitmap(sPicPaht);
    if (lPicLong > 400)
    {
    MessageBox.Show("此文件大小為" + lPicLong + "K;已超過最大限制的K范圍!");
    }
    else
    {
    Point ptLoction = new Point(bmPic.Size);
    if (ptLoction.X > picBox.Size.Width || ptLoction.Y > picBox.Size.Height)
    {
    picBox.SizeMode = PictureBoxSizeMode.Zoom;
    }
    else
    {
    picBox.SizeMode = PictureBoxSizeMode.CenterImage;
    }
    }
    picBox.LoadAsync(sPicPaht);
    lblName.Text = sPicName;
    lblLength.Text = lPicLong.ToString() + " KB";
    lblSize.Text = bmPic.Size.Width.ToString() + "×" + bmPic.Size.Height.ToString();
    }
    }
     
    第四步:测试控件
    按F5启动调试,弹出如下窗体:
    单击“打开”按钮,弹出打开文件对话框:
    选择一张图片,单击“打开”,可以看到在picBox上显示了打开的图片:
    第五步:查看成生的控件文件,到该项目文件目录下的bin->debug中可找到。
     
    下篇:控件测试
    第一步:新建一个C# Windows 应用程序,名为TestMyButton.
     
    第二步:增加自定义的用户控件
    右键单击工具箱中任意一个控件,弹出右键菜单如下:
    单击“选择项”,弹出如下对话框:
    单击“浏览”,弹出打开对话框:
    选中控件文件 mybutton.dll ,单击“打开”按钮,回到自定义工具箱,系统会默认把你刚才选中的控件打上 勾。
    返回vs编辑器,可看到工具箱中多出了一个UserControl:
     
    第三步:拖动1个自定义的控件到测试窗口
    第四步 测试程序
    单击“打开”按钮:
    选择一个图片,打开,显示该图:
    测试成功。
     
     
     
  • 相关阅读:
    LeetCode 623. Add One Row to Tree
    LeetCode 894. All Possible Full Binary Trees
    LeetCode 988. Smallest String Starting From Leaf
    LeetCode 979. Distribute Coins in Binary Tree
    LeetCode 814. Binary Tree Pruning
    LeetCode 951. Flip Equivalent Binary Trees
    LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List
    LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal
    LeetCode 687. Longest Univalue Path
    LeetCode 428. Serialize and Deserialize N-ary Tree
  • 原文地址:https://www.cnblogs.com/xiongxuanwen/p/1992387.html
Copyright © 2011-2022 走看看