C#入门经典---Windows笔记(1)

尝试着看beginning visual C sharp 2010的英文版,看不懂就看中文的翻译~~~继续好好学习,天天向上!!!奋斗

---------------------------------------------------------------------------------------------------------------------------------------------------

**一些控件的属性

Bottom \ Top \ Left \ Right:窗体的边缘到控件的边缘

Height \ Width:控件自己的高度和宽度

Anchor:控件随容器变化的属性

Dock:Docks a control to the edges of its container.(控件停靠在容器边缘)

Enabled:通常true表示可以接受来自用户的输入;false则反之。The edge of the control relative to the  edge of its container

Parent:父控件

Name:在代码中引用。

TabIndex:控件在容器中的标签顺序号

TabStop:只是是否可以使用Tab键

Tag:这个值通常不由控件本身使用,而是在控件中存储控件的信息。当windows设计器给这个属性赋值,只能是一个字符串。

Visible:指定控件在运行时时候可见。

**处理事件的基本方式

1.双击控件:默认事件

2.单击属性窗口的事件列表,双击事件。

3.自己添加订阅该事件的代码。

**Button控件(System.Windows.Froms.ButtonBase)

派生于ButtonBase的三个控件:Button、CheckBox、RadioButton

Button的属性

FlatStyle:改变按钮样式,如图的四个样式:

Enabled

Image          

ImageAlign

达到上面的效果一般用到的属性有Image、ImageAlign和TextAlign

**RadioButton \ CheckBox:需要GroupBox或其他一些容器

*RadioButton:

RadioButton 的属性

Appearance:Nomal/Button

AutoCheck:True / False

CheckAlign:小圆圈的位置

Checked:默认选中

RadioButton的事件

CheckedChanged

Click :[ 如果单击按钮的AutoCheck的属性是false,则按钮不会被选中,只引发click事件]

*CheckBox

属性:

CheckState:Check  \ Unchecked \ Indeterminate [ 当复选框的状态是Indeterminate 时,空间旁边的复选款通常是灰色。表示复选框当前值是无效的,或者无法确定]

ThreeState:当这个属性是false时,用户就不能把CheckState属性改为Indeterminate。但仍可以在代码中把CheckState属性改为indeterminate。

事件:

CheckedChanged:当复选框的Checked属性发生改变时,就引发该事件。 但是当TreeState的属性为True,且状态是Indeterminate状态时,单击复选框可能不会改变checked属性。

CheckedStateChanged:当CheckedState属性改变时就会引发该事件。

**Lable \ LinkLable

**TextBox \ RichTextBox===>>(派生于)TextBoxBase

相关属性:CausesValidation:只是组件是否引发验证事件( validating \ validated)

事件 Enter \ Leave \ Validating \ Validated

          KeyDown \ KeyPress \ KeyUp

          TextChanged

 **RichTextBox

属性

事件:LinkClicked \ Protected \ SelectionChanged

**ListBox和CheckedListBox控件

CheckedListBox===>ListBox===>ListControl

属性:

SelectedIndex:从0开始。若可以多选,则保存多个项中的第一个。

ColumnWidth:指定列宽

MultiColumn:列表框可以有多列,使用这个属性可以获取是否采用多列形式的信息,也可以设置是否采用多列形式。

CheckOnClick:只要点击到某Item,就会改变复选框中的状态。

...

方法:

ClearSelected()

FindString ()

FindStringExact()

GetSelected()

SetSelected()

ToString()

set/GetItemChecked()

set/GetItemCheckState()

事件:

ItemCheck()

SelectedIndexChanged()

比如把CheckedListBox 中选中的项移动到ListBox中,对一个属性的应用:

    private void buttonMove_Click(object sender, EventArgs e)
    {
      // Check if there are any checked items in the CheckedListBox.
      if (checkedListBoxPossibleValues.CheckedItems.Count > 0)
      {
        // Clear the ListBox we’ll move the selections to
        listBoxSelected.Items.Clear();

        // Loop through the CheckedItems collection of the CheckedListBox
        // and add the items in the Selected ListBox
        foreach (string item in checkedListBoxPossibleValues.CheckedItems)
        {
          listBoxSelected.Items.Add(item.ToString());
        }

        // Clear all the checks in the CheckedListBox
        for (int i = 0; i < checkedListBoxPossibleValues.Items.Count; i++)
          checkedListBoxPossibleValues.SetItemChecked(i, false);
      }
    }

**ListView:Windows中为显示文件和文件夹提供了很多方式。

属性 、 方法、 事件

**ListViewItem

列表试图中的选项总是ListViewItem类的一个实例。ListViewItem包含要显示的信息。ListViewItems对象有一个SubItem属性,其中包含另一类ListViewSubItem的实例。如果ListView控件属于Details或Tile模式下,这些子选项就是显示出来。每个子选项表示列表视图中的一列。子选项和主选项之间的区别是,子选项不能显示图标。

SubItems.ListViewSubItems->Items.ListViewItems->ListView

**ImageList:用于村吃在窗体的其他空间中使用的图像。ListView中,需要两个ImageList控件,才能显示大图像和小图像。

**ColumHeader:当ListView控件处于Details模式下,ColumnHeader为要显示的列提供一个标题。

 

***TabControl

TabControl包含了TabPages。TabPages的工作方式与GroupBox控件非常相似,就是把控件组合起来。

 属性:

Alignmnet \ Appearance \ HotTrack :如果这个属性设置为True,则当鼠标指针滑过控件上的选项卡时,其外观就会改变。\ Multiline \ RowCount \ SelectedInex \

SelectedTab :返回或设置选中的选项卡。注意这个属性在TabPages的实例上使用。 \ TabCount \ TabPages

用SelectedTab和SelectedIndex来确定当前显示的是哪个选项卡;SelectedTab返回TabPage对象,当没有选项卡时,返回Null。如果SelectedIndex没有选项卡,则返回-1。

小技巧:

1.为了确保用户在输入完信息之前单击OK按钮,可以把OK按钮的Enabled属性设置为false.这应在窗体的构造函数中设置,而不是在属性窗口中设置。如果要在构造函数中设置属性,应确保在调用InitializeComponent()中生成的代码之后 ,在设置这些属性

(1)public Form1()

{

InitializeComponent();

buttonOK.Enabled=false;

}

(2)在满足条件后设置buttonOK.Enabled=(bool的判断表示式)

2. 对于Age的文本框设置 :要求只输入正数,不想要的字符在文本框中不显示,字符数控制为3。

(1)设置属性的MaxLength:3

(2)使用KeyPress事件

    private void textBoxAge_KeyPress(object sender, KeyPressEventArgs e)
    {//0-9之间数字的ASCII值48-57,其中ASCII中8代表退格键。
        if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
        {
            //满足条件时才告诉控件处理事件
            //System.Windos.Form.KeyPressEventhandler
            e.Handled = true;
        }
    }

3.设置为窗体的颜色:

textboxOK.BackColor = System.Drawing.SystemColors.Window;

4.要是一和GroupBox中,有两个RadioButton,其中一个的Checked设置为True,那么可以用下面的语句来控制另外一个RadioButton的值

 string output = "Sex: " + (string)(radioButtonFemale.Checked ? "Female": "Male") ;

5.RichTextBox相关设置

(1)Font(Bold \ Underline \ Italic )

        private void buttonBold_Click(object sender, EventArgs e)
        {
            Font oldFont;
            Font newFont;

            // Get the font that is being used in the selected text
            oldFont = this.richTextBox.SelectionFont;

            // If the font is using bold style now, we should remove the
            // Formatting.
            if (oldFont.Bold)
                newFont = new Font(oldFont, oldFont.Style & ~FontStyle.Bold);
            else
                newFont = new Font(oldFont, oldFont.Style | FontStyle.Bold);

            // Insert the new font and return focus to the RichTextBox.
            this.richTextBox.SelectionFont = newFont;
            this.richTextBox.Focus();
        }

(2)Center

        private void buttonCenter_Click(object sender, EventArgs e)
        {
        if (this.richTextBox.SelectionAlignment == HorizontalAlignment.Center)
            this.richTextBox.SelectionAlignment = HorizontalAlignment.Left;
        else
            this.richTextBox.SelectionAlignment = HorizontalAlignment.Center;
        this.richTextBox.Focus();
        }

(3)Size:(KeyPress事件和Validated事件)

        private void textBoxSize_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Remove all characters that are not numbers, backspace, or enter.
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13)
            {
                e.Handled = true;
            }
            else if (e.KeyChar == 13)
            {
                // Apply size if the user hits enter
                TextBox txt = (TextBox)sender;

                if (txt.Text.Length > 0)
                    ApplyTextSize(txt.Text);
                e.Handled = true;
                this.richTextBox.Focus();
            }
        }

        private void textBoxSize_Validated(object sender, EventArgs e)
        {
            TextBox txt = (TextBox)sender;

            ApplyTextSize(txt.Text);
            this.richTextBox.Focus();
        }

        private void ApplyTextSize(string textSize)
        {
            // Convert the text to a float because we’ll be needing a float shortly.
            float newSize = Convert.ToSingle(textSize);
            FontFamily currentFontFamily;
            Font newFont;

            // Create a new font of the same family but with the new size.
            currentFontFamily = this.richTextBox.SelectionFont.FontFamily;
            newFont = new Font(currentFontFamily, newSize);

            // Set the font of the selected text to the new font.
            this.richTextBox.SelectionFont = newFont;
        }

(4)处理RichTextBox的链接事件  (为什么我尝试了以后网页打开却链接不到站点呢???疑问)

    private void richTextBoxText_LinkClicked(object sender, LinkClickedEventArgs e)
    {
      System.Diagnostics.Process.Start(e.LinkText);
    }

(5)加载和保存文件

    private void buttonLoad_Click(object sender, EventArgs e)
    {
      // Load the file into the RichTextBox.
      try
      {
        richTextBoxText.LoadFile("Test.rtf");
      }
      catch (System.IO.FileNotFoundException)
      {
        MessageBox.Show("No file to load yet");
      }
    }

    private void buttonSave_Click(object sender, EventArgs e)
    {
      // Save the text.
      try
      {
        richTextBoxText.SaveFile("Test.rtf");
      }
      catch (System.Exception err)
      {
        MessageBox.Show(err.Message);
      }
    }

(6)在CheckListBox中添加一项:1.在Items属性中添加2.在窗体初始化后面的代码中添加:checkedListBoxPossibleValues.Items.Add("Ten");

7.ListView

(1)在ListView中添加列

      ColumnHeader colHead;

      // First header
      colHead = new ColumnHeader();
      colHead.Text = "Filename";
      listViewFilesAndFolders.Columns.Add(colHead); // Insert the header





(2)将硬盘上的文件夹和文件加载到ListView上

      //用硬盘上的文件和文件夹填充列表视图
    private void PaintListView(string root)
    {
      try
      {
        // Two local variables that are used to create the items to insert
        ListViewItem lvi;
        ListViewItem.ListViewSubItem lvsi;

        // If there’s no root folder, we can’t insert anything.
        if (string.IsNullOrEmpty(root))
          return;

        // Get information about the root folder.
        DirectoryInfo dir = new DirectoryInfo(root);

        // Retrieve the files and folders from the root folder.
        DirectoryInfo[] dirs = dir.GetDirectories(); // Folders
        FileInfo[] files = dir.GetFiles();           // Files

        // Clear the ListView. Note that we call the Clear method on the
        // Items collection rather than on the ListView itself.
        // The Clear method of the ListView remove everything, including column
        // headers, and we only want to remove the items from the view.
        listViewFilesAndFolders.Items.Clear();

        // Set the label with the current path.
        labelCurrentPath.Text = root;

        // Lock the ListView for updates.
        listViewFilesAndFolders.BeginUpdate();

        // Loop through all folders in the root folder and insert them.
        foreach (DirectoryInfo di in dirs)
        {
          // Create the main ListViewItem.
          lvi = new ListViewItem();
          lvi.Text = di.Name; // Folder name
          lvi.ImageIndex = 0; // The folder icon has index 0
          lvi.Tag = di.FullName; // Set the tag to the qualified path of the
          // folder

          // Create the two ListViewSubItems.
          lvsi = new ListViewItem.ListViewSubItem();
          lvsi.Text = ""; // Size—a folder has no size and so this column
          // is empty
          lvi.SubItems.Add(lvsi); // Add the subitem to the ListViewItem

          lvsi = new ListViewItem.ListViewSubItem();
          lvsi.Text = di.LastAccessTime.ToString(); // Last accessed column
          lvi.SubItems.Add(lvsi); // Add the subitem to the ListViewItem.

          // Add the ListViewItem to the Items collection of the ListView.
          listViewFilesAndFolders.Items.Add(lvi);
        }

        // Loop through all the files in the root folder.
        foreach (FileInfo fi in files)
        {
          // Create the main ListViewItem.
          lvi = new ListViewItem();
          lvi.Text = fi.Name; // Filename
          lvi.ImageIndex = 1; // The icon we use to represent a folder has
          // index 1.
          lvi.Tag = fi.FullName; // Set the tag to the qualified path of the
          // file.

          // Create the two subitems.
          lvsi = new ListViewItem.ListViewSubItem();
          lvsi.Text = fi.Length.ToString(); // Length of the file
          lvi.SubItems.Add(lvsi); // Add to the SubItems collection

          lvsi = new ListViewItem.ListViewSubItem();
          lvsi.Text = fi.LastAccessTime.ToString(); // Last Accessed Column
          lvi.SubItems.Add(lvsi); // Add to the SubItems collection

          // Add the item to the Items collection of the ListView.
          listViewFilesAndFolders.Items.Add(lvi);
        }

        // Unlock the ListView. The items that have been inserted will now
        // be displayed.
        listViewFilesAndFolders.EndUpdate();
      }
      catch (System.Exception err)
      {
        MessageBox.Show("Error: " + err.Message);
      }
    }

    private void listViewFilesAndFolders_ItemActivate(object sender, EventArgs e)
    {
      // Cast the sender to a ListView and get the tag of the first selected
      // item.
      System.Windows.Forms.ListView lw = (System.Windows.Forms.ListView)sender;
      string filename = lw.SelectedItems[0].Tag.ToString();

      if (lw.SelectedItems[0].ImageIndex != 0)
      {
        try
        {
          // Attempt to run the file.
          System.Diagnostics.Process.Start(filename);
        }
        catch
        {
          // If the attempt fails we simply exit the method.
          return;
        }
      }
      else
      {
        // Insert the items.
        PaintListView(filename);
        folderCol.Add(filename);
      }
    }

(3) //为了允许用户通过双击ListView中的选项来浏览文件夹,需要订阅ItemActivate事件

    //为了允许用户通过双击ListView中的选项来浏览文件夹,需要订阅ItemActivate事件
    private void listViewFilesAndFolders_ItemActivate(object sender, EventArgs e)
    {
      // Cast the sender to a ListView and get the tag of the first selected
      // item.
      System.Windows.Forms.ListView lw = (System.Windows.Forms.ListView)sender;
        //Tag包含被双击的文件或文件夹的完全限定路径。
      string filename = lw.SelectedItems[0].Tag.ToString();
        //索引为0的图像是一个文件夹;
        //如果选型是一个文件,就试着加载它。
      if (lw.SelectedItems[0].ImageIndex != 0)
      {
        try
        {
          // Attempt to run the file.
          System.Diagnostics.Process.Start(filename);
        }
        catch
        {
          // If the attempt fails we simply exit the method.
          return;
        }
      }
      else
      {
        // Insert the items.
        PaintListView(filename);
        folderCol.Add(filename);
      }
    }

(4)Back按钮的设计

    private void buttonBack_Click(object sender, EventArgs e)
    {
      if (folderCol.Count > 1)
      {
          //加载到最后第二个
        PaintListView(folderCol[folderCol.Count - 2].ToString());
          //删除最后一个
        folderCol.RemoveAt(folderCol.Count - 1);
      }
      else
          //加载当前一个
        PaintListView(folderCol[0].ToString());
    }

(8)view的切换

    private void radioButtonLargeIcon_CheckedChanged(object sender, EventArgs e)
    {
      RadioButton rdb = (RadioButton)sender;
      if (rdb.Checked)
          this.listViewFilesAndFolders.View = View.LargeIcon;
        //View.SmallIcon-View.List-View.Details-View.Tile
    }



 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值