プログレスバーのモードを変更するコードを紹介します。
プログレスバーのモードを変える場合はプログレスバーに対し、SendMessage関数を使用してウィンドウメッセージをプログレスバーに送信します。
今回は、ProgressBarを派生させたコンポーネントを作成してSendMessage部分を隠蔽したProgressBarコントロールを作成します。
下記のVistaProgress.csファイルを作成しプロジェクトに追加します。プロジェクトに追加されるとツールボックスにVistaProgressBarコンポーネントが表示されます。
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Drawing;
namespace ProgressBar
{
[ToolboxBitmap(typeof(System.Windows.Forms.ProgressBar))]
public class VistaProgressBar : System.Windows.Forms.ProgressBar
{
public delegate void StateChangedHandler(object source, vState State);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern uint SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam);
private vState _State = vState.Normal;
public enum vState { Normal, Pause, Error }
private const int WM_USER = 0x400;
private const int PBM_SETSTATE = WM_USER + 16;
private const int PBST_NORMAL = 0x0001;
private const int PBST_ERROR = 0x0002;
private const int PBST_PAUSED = 0x0003;
[Category("Behavior")]
[Description("Event raised when the state of the Control is changed.")]
public event StateChangedHandler StateChanged;
[Category("Behavior")]
[Description("This property allows the user to set the state of the ProgressBar.")]
[DefaultValue(vState.Normal)]
public vState State
{
get
{
if (Environment.OSVersion.Version.Major < 6)
return vState.Normal;
if (this.Style == System.Windows.Forms.ProgressBarStyle.Blocks) return _State;
else return vState.Normal;
}
set
{
_State = value;
if (this.Style == System.Windows.Forms.ProgressBarStyle.Blocks)
ChangeState(_State);
}
}
private void ChangeState(vState State)
{
if (Environment.OSVersion.Version.Major > 5) {
SendMessage(this.Handle, PBM_SETSTATE, PBST_NORMAL, 0);
switch (State) {
case vState.Pause:
SendMessage(this.Handle, PBM_SETSTATE, PBST_PAUSED, 0);
break;
case vState.Error:
SendMessage(this.Handle, PBM_SETSTATE, PBST_ERROR, 0);
break;
default:
SendMessage(this.Handle, PBM_SETSTATE, PBST_NORMAL, 0);
break;
}
if (StateChanged != null)
StateChanged(this, State);
}
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == 15)
ChangeState(_State);
base.WndProc(ref m);
}
}
}
ツールボックスからVistaProgressBarコンポーネントを選択しフォームに張り付けます。VistaProgressBarコンポーネントには、Statusプロパティが追加されており、こちらの値を変更します。
StatusプロパティをPauseに変更すると、プログレスバーが黄色くなることが確認できます。
同様に、StatusプロパティをErrorに変えるとプログレスバーが赤くなります。
また、Styleプロパティも追加されています。StyleプロパティをMarqueeに変更するとプログレスバーの表示が待機中モードになります。StyleプロパティをContinuousにすると、Valueの位置までアニメーションする効果のプログレスバーになります。