Visual Basic 2005 程式設計 第 14 章 Windows Forms 控制項
14-1 認識 Windows Forms Windows Forms 是全新的視窗應用程式介面 Web Forms 與 Web Services 組成全新的網際網路應用程式介面,.NET Framework 將之統稱為 ASP.NET System.Windows.Forms 命名空間提供的成員
14-2 Windows Forms 與控制項的新增功能 預設的表單物件 舊版 ( 需要宣告 ): sub Main() Dim f As New Form1 f.show() End Sub 新版 ( 預設 ): Form1.Show() 或 My.Forms.Form1.Show()
取代舊有的 Windows Forms 控制項提供增強型 :MenuStrip ToolStrip ContextMenuStrip. 取代 : MainMenu ToolBar ContextMenu 欲使用舊有控制項可在工具箱上按滑鼠右鍵再從 [ 選擇項目 ] 的 [ 選擇工具項目 ] 中選取 新增的控制項 : WebBrowser: 顯示 HTML 及瀏覽網站 MaskedTextBox: 透過遮罩驗證使用者輸入資料須符合規劃既有控制項的改變增加既有控制項之屬性
14-3 設計階段的表單 14-3-1 建立表單 1. 啟動 Visual Studio 2005 2. 選取 [ 檔案 ] \ [ 新增專案 ] 3. 選擇 [Visual Basic 專案 ] 類型及 [Windows 應用程 式 ] 範本, 並輸入專案名稱, 然後按 [ 確定 ]
如果您想要在專案內加入其它表單, 那麼可以從功能表列選取 [ 專案 ] \ [ 加入 Windows Form], 然後依照下圖操作 :
如果您想要在專案內加入其它表單, 但這個表單必須繼承自之前建立的表單, 而不是繼承自 System.Windows.Forms.Form 類別, 那麼可以從功能表列選取 [ 專案 ] \ [ 加入 Windows Form], 然後依照下圖操作 :
14-3-2 設定起始表單
14-3-3 設定表單的屬性
表單的外觀屬性 BackColor BackgroundImage BackgroundImageLayout Cursor ForeColor RightToLeft Text UseWaitCursor Font FormBorderStyle
表單的視窗樣式屬性 ControlBox HelpButton Icon IsMdiContainer MainMenuStrip MaximizeBox MaximizeBox Opacity
ShowIcon ShowInTaskBar SizeGripStyle TopMost TransparencyKey
表單的配置方式 單一文件介面 (SDI) 多重文件介面 (MDI) 總管樣式介面 (Explorer-Style Interface) 表單的配置屬性 AutoScaleMode AutoSizeMode AutoScroll AutoScrollMargin AutoScrollMinSize
Location MaximumSize MinimumSize Padding Size StartPosition WindowState 表單的配置屬性 Name
表單的行為屬性 AllowDrop ContextMenuStrip Enabled ImeMode 表單的其他屬性 AcceptButton CancelButton KeyPreview
14-4 執行階段的表單 相關的控制項事件 :Activated BackcolorChanged Click Closed Closing FormClosed FormClosing ControlAdded ControlRemoved CursorChanged Deactivate DoubleClick DragDrop DragEnter DragLeave DragOver Eeter GotFocus HandleCreated HandleDestroyed HelpRequested KeyDown KeyPress KeyUp Layout Leave Load LocationChanged LostFocus MenuComplete MenuStart Move MouseDown MouseEnter MouseHover MouseLeave MouseMove MouseUp MouseWheel MouseCaptureChanged MouseClick MouseDoubleClick Paint Resize SizeChanged TextChanged Validated Validating VisibleChanged
14-5 文字編輯控制項 14-5-1 TextBox ( 文字方塊 ) 文字方塊的外觀屬性 BackColor BorderStyle Cursor Font ForeColor ScrollBars Text TextAlign UseWaitCursor
文字方塊的行為屬性 AcceptsReturn AcceptsTab AllowDrop CharacterCasting ContextMenuStrip Enabled HideSelection MaxLength
Multiline PasswordChar ReadOnly TabIndex TabStop Visible WordWrap UseSystemPasswordChar
文字方塊的配置屬性 Anchor Dock Location Size Margin MaximumSize MinimumSize
文字方塊的其它屬性 AutoCompleteCustomSource AutoCompleteMode AutoCompleteSource
14-5-2 RichTextBox RichTextBox 的屬性 AutoWordSelection BulletIndent DetectUrls EnableAutoDragDrop ShowSelectionMargin ZoomFactor
RichTextBox 的格式化屬性 SelectedText SelectionAlignment SelectionBullet SelectionCharOffset SelectionColor SelectionFont SelectionIndent SelectionHangingIndent SelectionRightIndent
SelectionStart SelectionLength SelectionProtected SelectionType SelectionTabs
14-5-3 MaskedTextBox MaskedTextBox 的格式化屬性 PromptChar AllowPromptAsInput AsciiOnly BeepOnError Mask
14-6 命令控制項 14-6-1 Button ( 按鈕 ) Button 的外觀屬性 BackColor BackgroundImage BackgroundImageLayout Cursor UseWaitCursor FlatStyle UseMnemonic
Font ForeColor Image ImageAlign ImageIndex ImageList Text TextAlign
Button 的行為屬性 AllowDrop ContextMenuStrip DialogResult Enabled TabIndex TabStop Visible
14-6-2 NotifyIcon ( 通知圖示 ) 比較重要的屬性有 : Icon Text BalloonTipIcon BalloonTipText BalloonTipTitle
14-7 文字顯示控制項 14-7-1 Label ( 標籤 ) Label 的外觀屬性 BackColor BorderStyle Cursor FlatStyle ForeColor Font Image
ImageAlign ImageIndex ImageList RightToLeft Text TextAlign UseMnemonic UseWaitCursor
Label 的行為屬性 AllowDrop AutoEllipsis ContextMenuStrip Enabled TabIndex UseCompatibleTextRendering Visible
14-7-2 LinkLabel ( 超連結標籤 ) LinkLabel 的屬性 ActiveLinkColor DiabledLinkColor LinkColor LinkVisited VisitedLinkColor LinkBehavior LinkArea
14-8 影像控制項 14-8-1 PictureBox ( 影像方塊 ) PictureBox 的外觀屬性 BackColor BackgroundImage BackgroundImageLayout UseWaitCursor
PictureBox 的行為屬性 ContextMenuStrip Enabled SizeMode Visible
14-8-2 ImageList ( 影像清單 ) ImageList 控制項可以用來儲存圖片清單, 以便稍後經由其它控制項顯示
ImageList 的外觀屬性 ColorDepth Images ImageList 的行為屬性 ImageSize TransparentColor
14-9 清單控制項 14-9-1 CheckBox ( 核取方塊 ) CheckBox 的屬性 Appearance CheckAlign Checked CheckState AutoCheck ThreeState
14-9-2 RadioButton ( 選項按鈕 )
14-9-3 ListBox ( 清單方塊 ) ListBox 的屬性 ColumnWidth HorizontalExtent HorizontalScrollBar IntegralHeight MultiColumn ScrollAlwaysVisible SelectedIndex
SelectedIndices SelectedItem SelectedItems SelectionMode Sorted
14-9-4 CheckedListBox ( 核取清單方塊 )
14-9-5 ComboBox ( 下拉式清單 )
14-9-6 DomainUpDown DomainUpDown 控制項可以用來在表單上插入一個由上下箭頭來做選擇的清單
14-9-7 NumericUpDown NumericUpDown 控制項可以用來在表單上插入一個由上下箭頭來遞增或遞減數字的清單
14-9-8 ListView ( 清單檢視 ) ListView 控制項可以用來在表單上插入清單檢視, 提供了大型圖示 小型圖示 清單 詳細資料及標題等五種檢視模式
ListView 的屬性 CheckBoxes CheckedIndices CheckedItems FullRowSelect GridLines View Activation AllowColumnReorder AutoArrange Columns HeaderStyle HideSelection
HoverSelection Items LabelEdit LabelWrap LargeImageList MultiSelect Scrollable SmallImageList Sorting StateImageList OwnerDraw BackgroundImageTiled
14-9-9 TreeView ( 樹狀檢視 ) TreeView 的屬性 CheckBoxes ItemHeight FullRowSelect HideSelection HotTracking Indent LabelEdit Nodes PathSeparator
Scrollable ShowLines ShowPlusMinus ShowRootLines Sorted DrawMode ShowNodeToolTips
14-10 日期時間控制項 14-10-1 DateTimePicker ( 日期時間選取器 ) DateTimePicker 的屬性如下 : Format ShowCheckBox ShowUpDown MaxDate MinDate Value
14-10-2 MonthCalendar ( 月曆 ) MonthCalendar 的屬性 CalendarDimentions TitleBackcolor TitleForecolor TrailingForeColor FirstDayOfWeek MaxDate MinDate MaxSelectionCount ScrollChange
SelectionEnd SelectionStart SelectionRange ShowToday ShowTodayCircle ShowWeekNumbers TodayDate
14-11 功能表 工具列與狀態列控制項 14-11-1 MenuStrip ( 功能表 )
ToolStripMenuItem 的屬性 Checked CheckState DisplayStyle Text TextAlign TextDirection Image ImageAlign ImageScaling ImageTransparentColor
ShortcutKeyDisplayString AutoSize AutoToolTip CheckOnClick Enabled ToolTipText Visible ShortcutKeys ShowShortcutKeys DropDownItems
14-11-2 ContextMenuStrip ( 快顯功能表 )
14-11-3 ToolStrip ( 工具列 )
14-11-4 StatusStrip ( 狀態列 ) StatusStripStatusLabel 的屬性 ActiveLinkColor BorderSides BorderStyle DisplayStyle Image ImageAlign ImageScaling ImageTransparentColor LinkColor LinkVisited Spring
Text TextAlign TextDirection AutoSize AutoToolTip Enabled VisitedLinkColor IsLink LinkBehavior ToolTipText
14-12 容器控制項 14-12-1 GroupBox ( 群組方塊 ) GroupBox 控制項可以用來插入群組方塊, 以放置性質相似的表單欄位
14-12-2 Panel ( 面板 ) Panel 控制項的用途和 GroupBox 控制項一樣是將性質相似的表單欄位放置在一個群組, 不同的是 Panel 控制項可以擁有捲軸, 只要將其 AutoScroll 屬性設定為 [True] 即可
14-12-3 FlowLayoutPanel FlowLayoutPanel 控制項是 Windows Forms 2.0 新增的控制項, 用途和 Panel 控制項一樣是將性質相似的表單欄位放置在一個群組, 不同的是 FlowLayoutPanel 控制項可以藉由其 FlowDirection 屬性設定以水平或垂直的資料流動方向排列表單內容
14-12-4 TableLayoutPanel TableLayoutPanel 控制項是 Windows Forms 2.0 新增的控制項, 它會在格線中排列表單內容
14-12-5 SplitContainer SplitContainer 控制項包含兩個可移動的分隔列所分隔的面板
14-12-6 TabControl ( 標籤 ) TabControl 的屬性 ImageList Alignment Appearance ContextMenuStrip ItemSize Multiline ShowToolTips SizeMode TabCount TabPages
14-13 對話方塊控制項 14-13-1 FontDialog ( 字型對話方塊 ) FontDialog 的屬性 AllowSimulations AllowVectorFonts AllowVerticalFonts Color Font FontMustExist MaxSize MinSize
ScriptsOnly ShowApply ShowColor ShowEffects ShowHelp
14-13-2 ColorDialog ( 色彩對話方塊 ) ColorDialog 的屬性如下 : AllowFullOpen AnyColor Color FullOpen ShowHelp SolidColorOnly
14-13-3 SaveFileDialog ( 另存新檔對話方塊 ) SaveFileDialog 的屬性 AddExtension CheckFileExists CheckPathExists CreatePrompt DefaultExt DereferenceLinks FileName FileNames Filter
FilterIndex InitialDirectory OverwritePrompt Title RestoreDirectory ShowHelp SupportMultiDottedExtensions ValidateNames
14-13-4 OpenFileDialog ( 開啟舊檔對話方塊 )
14-13-5 FolderBrowserDialog ( 瀏覽資料夾對話方塊 ) FolderBrowserDialog 的屬性 Description RootFolder SelectedPath ShowNewFolderButton
14-14 其它控制項 14-14-1 TrackBar ( 滑動軸 ) TrackBar 的屬性 Orientation LargeChange SmallChange TickFrequency TickStyle Maximum Minimum Value
14-14-2 Timer ( 計時器 ) 屬性 Interval Enabled 方法 Start Stop
14-14-3 ProgressBar ( 進度列 ) ProgressBar 的屬性 MarqueeAnimationSpeed Maximum Minimum Step Style Value
14-15 Windows Forms 的 GDI+ 繪圖 14-15-1 建立 Graphics 物件 方法一 : Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As _ System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint Dim MyGraphics As Graphics MyGraphics = e.graphics ' 接下來可以撰寫進行繪圖的程式碼 End Sub 方法二 : Private Sub Form1_Paint(ByVal sender As System.Object, ByVal e As _ System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint Dim MyGraphics As Graphics MyGraphics = Me.CreateGraphics() ' 接下來可以撰寫進行繪圖的程式碼 End Sub
14-15-2 建立色彩 畫筆與筆刷 建立色彩, 例如 : Dim MyColor As Color = Color.FromArgb(0, 255, 0) 建立畫筆, 例如 : Dim mypen As New Pen(Color.Black, 5) 建立筆刷, 類型如下 : SolidBrush HatchBrush TextureBrush LinearGradientBrush PathGradientBrush
14-15-3 繪製線條與形狀 Point 結構和 Rectangle 結構 Dim MyPoint() As Point = {New Point(x1, y1), New Point(x2, y2), New Point(x3, y3)...} Dim MyRec As New Rectangle(x, y, w, h) 方法 DrawBezier(pen, pt1, pt2, pt3, pt4) DrawCurve(pen, points) DrawClosedCurve(pen, points) DrawEllipse(pen, x, y, width, height) DrawLine(pen, x1, y1, x2, y2)
DrawPolygon(pen, points) DrawRectangle(pen, x, y, width, height) DrawArc(pen, x, y, width, height, startangle, sweepangle) DrawPie(pen, x, y, width, height, startangle, sweepangle) FillClosedCurve(brush, points) FillEllipse(brush, x, y, width, height) FillPie(brush, x, y, width, height, startangle, sweepangle) FillPolygon(brush, points) FillRectangle(brush, x, y, width, height)
ResetTransform() RotateTransform(angle) ScaleTransform(sw, sh) TranslateTransform(dx, dy) Clear(color) Dispose() Save()
依照指示在表單上繪製如下的線條或形狀, 裡面定義了三種畫筆, 色彩分別為 Red Blue Green, 寬度分別為 1 3 5 個像素
依照指示將前一個隨堂練習的封閉圖形填滿色彩
依照指示在表單上繪製如下圖形, 前者是繪製 10 個圓形, 每個圓形之間位移 10 像素, 後者是繪製 36 個矩形, 每個矩形之間旋轉 10 度
14-15-4 繪製文字 1. 首先, 建立 Graphices 物件 2. 接著, 建立用來繪製文字的筆刷 3. 繼續, 建立用來繪製文字的字型, 例如 : Dim MyFont As New Font(" 標楷體 ", 20, FontStyle.Italic) 4. 呼叫 Graphics 物件提供的 DrawString() 方法繪製文字, 例如 : MyGraphics.DrawString("Visual Basic 2005 程式設計 ", MyFont, MyBrush, 10, 10)
將前面的步驟整合在一起, 可以得到如下結果 : Private Sub Form1_Paint(ByVal sender As Object, ByVal e As _ System.Windows.Forms.PaintEventArgs) Handles Me.Paint Dim MyGraphics As Graphics = e.graphics Dim MyBrush As New LinearGradientBrush(ClientRectangle, Color.Red, _ Color.Yellow, LinearGradientMode.Horizontal) Dim MyFont As New Font(" 標楷體 ", 20, FontStyle.Italic) MyGraphics.DrawString("Visual Basic 2005 程式設計 ", MyFont, MyBrush, 10, 10) End Sub
14-15-5 顯示影像 1. 首先, 建立 Graphices 物件 2. 接著, 建立用來表示欲顯示之影像的物件, 例如 : Dim MyBitmap As New Bitmap("C:\img1.bmp") 3. 呼叫 Graphics 物件提供的 DrawImage() 方法繪製圖形, 例如 : MyGraphics.DrawImage(MyBitmap, 10, 10)
將前面的步驟整合在一起, 就可以得到如下結果 Private Sub Form1_Paint(ByVal sender As Object, ByVal e As _ System.Windows.Forms.PaintEventArgs) Handles Me.Paint Dim MyGraphics As Graphics = e.graphics Dim mybitmap As New Bitmap("C:\Documents and Settings\Jerry\My Documents\" & _ Visual Studio 2005\Projects\MyProj-Form42\MyProj- Form42\img1.bmp ") MyGraphics.DrawImage(myBitmap, 10, 10) End Sub
14-16 Windows Forms 的列印支援
1. 2. 3. 將 PrintPreviewDialog1 和 PrintDialog1 兩個控制項的 Document 屬性設定為 PrintDocument1, 表示欲進行預覽及列印的文件為 PrintDocument1
4. 撰寫 PrintDocument1 的 PrintPage 事件處理程序 Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As _ System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim MyGraphics As Graphics = e.graphics Dim MyBrush As New SolidBrush(Color.Black) Dim MyFont As New Font(" 新細明體 ", 12) MyGraphics.DrawString(TextBox1.Text, MyFont, MyBrush, 10, 10) End Sub 5. 撰寫 [ 預覽列印 ] 按鈕的 Click 事件處理程序 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click PrintPreviewDialog1.ShowDialog() End Sub
6. 在程式碼視窗中撰寫 [ 列印 ] 按鈕 (Button2) 的 Click 事件處理程序 Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button2.Click Dim Result As DialogResult = PrintDialog1.ShowDialog() If (Result = Windows.Forms.DialogResult.OK) Then PrintDocument1.Print() End If End Sub