C# 小技巧2

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(
thisnew EventArgs());
        }

      }



在界面程序中加入
_items.OnCollectionChanged 
+= new EventHandler(_items_OnCollectionChanged);
        
        
private void _items_OnCollectionChanged(object sender, EventArgs e)
        
{
            OnPaint();
        }
posted @ 2007-09-03 12:18  moonz-wu  阅读(379)  评论(0编辑  收藏  举报