C# 小技巧2

來源:互聯網
上載者:User
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();
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.