共用方式為


操作說明:使用 DateTimePicker 控制項顯示時間

如果您希望應用程式可讓使用者選取日期和時間,並在指定的格式中顯示該日期和時間,請使用 DateTimePicker 控制項。 下列程序示範如何使用 DateTimePicker 控制項來顯示時間。

使用 DateTimePicker 控制項顯示時間

  1. Format 屬性設定為 Time

    timePicker.Format = DateTimePickerFormat.Time;
    
    timePicker.Format = DateTimePickerFormat.Time
    
  2. DateTimePickerShowUpDown 屬性設定為 true

    timePicker.ShowUpDown = true;
    
    timePicker.ShowUpDown = True
    

範例

下列程式碼範例示範如何建立 DateTimePicker,可讓使用者僅能選擇一個時間。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TimePickerApplication
{
    public class Form1 : Form
    {
        public Form1()
        {
            InitializeTimePicker();
        }
        private DateTimePicker timePicker;

        private void InitializeTimePicker()
        {
            timePicker = new DateTimePicker();
            timePicker.Format = DateTimePickerFormat.Time;
            timePicker.ShowUpDown = true;
            timePicker.Location = new Point(10, 10);
            timePicker.Width = 100;
            Controls.Add(timePicker);
        }
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }
}
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    Public Sub New()
        InitializeTimePicker()

    End Sub
    Private timePicker As DateTimePicker


    Private Sub InitializeTimePicker()
        timePicker = New DateTimePicker()
        timePicker.Format = DateTimePickerFormat.Time
        timePicker.ShowUpDown = True
        timePicker.Location = New Point(10, 10)
        timePicker.Width = 100
        Controls.Add(timePicker)

    End Sub

    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())

    End Sub
End Class

編譯程式碼

這個範例需要:

  • System、System.Data、System.Drawing 和 System.Windows.Forms 組件的參考。

另請參閱