1. 產生滑鼠按住左鍵或右鍵的連續調用
在開發的時候我們有時需要產生一個滑鼠按下後的連續事件,比如說捲軸的上下箭頭按鈕,按住後就會連續滾動。那麼如何對一個普通按鈕來產生這樣的調用呢?可以有多種方法去解決比如時鐘,迴圈,線程和Application.DoEvent,不過比較好並且簡單的方法是用後台線程,所以我在這裡只講用線程的模式。
比如你有個一個按鈕叫_pgdnBtn, 你想對這個按鈕的左鍵按下進行連續處理, 處理函數是ToScroll。 private Button _pgdnBtn;
private Thread _loopMouseDownThread;
private bool _isDown;
void _pgdnBtn_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_isDown = true;
_isScrollDown = true;
_loopMouseDownThread = new Thread(new ThreadStart(ToScroll));
_loopMouseDownThread.IsBackground = true;
_loopMouseDownThread.Start();
}
}
private void ToScroll()
{
// when the mouse is keep down on the button, we will scroll this view
// until mouse up.
while (_isDown)
{
System.Threading.Thread.Sleep(THREAD_SLEEP_INTERVAL);
}
}
private void _pgdnBtn_MouseUp(object sender, MouseEventArgs e)
{
_isDown = false;
}
最後你需要定義一個Mouse Up事件來退出線程。
2. 同步資料與介面
有時候我們需要在資料變化的時候同步到介面中去,主要是調用介面程式中的函數。解決方式也有多種,比如通過屬性,事件和代表。這裡我覺得比較好的方式是事件,所以我主要講一下事件的方法是如何?的。
比如我們有一個資料集合叫PaintObjectCollection,我們需要在集合資料被添加的時候告訴介面集合元素髮生了變化, public class PaintObjectCollection : List<PaintObject>
{
// This event handler is used to call the DmPaintView UpdateItemsLocation
// function. That can keep the items location in the correct postion
//
public event EventHandler OnCollectionChanged;
public new void Add(PaintObject obj)
{
base.Add(obj);
if (null != OnCollectionChanged)
OnCollectionChanged(this, new EventArgs());
}
}
在介面程式中加入
_items.OnCollectionChanged += new EventHandler(_items_OnCollectionChanged);
private void _items_OnCollectionChanged(object sender, EventArgs e)
{
OnPaint();
}