2013-01-16 73 views
1

我只是想清除剪贴板文本,如果我的表格LostFocus。我的意思是,如果用户使用键盘或鼠标复制某些内容,必须在LostFocus事件中清除它,然后如果我的表单再次获得焦点,则需要返回文本。我怎样才能做到这一点?GotFocus事件不是在C#中创建LostFocus事件后出现的

string sValue = ""; 
public Form1() 
{ 
    InitializeComponent(); 
    this.LostFocus += new EventHandler(Form1_LostFocus); 
    this.GotFocus += new EventHandler(Form1_GotFocus); 
} 

void Form1_GotFocus(object sender, EventArgs e) 
{ 
    Clipboard.SetText(sValue); 
    textBox1.Text = Clipboard.GetText(); 
} 

void Form1_LostFocus(object sender, EventArgs e) 
{ 
    sValue = textBox1.Text; 
    Clipboard.Clear(); 
} 

这是行不通的; LostFocus事件被调用,但GotFocus没有被调用。我该如何解决这个问题?

回答

1
string sVal = ""; 
    public Form1() 
    { 
     InitializeComponent(); 
     this.Activated += new EventHandler(Form1_GotFocus); 
     this.Deactivate += new EventHandler(Form1_LostFocus); 

    } 

    void Form1_LostFocus(object sender, EventArgs e) 
    { 
     sVal = Clipboard.GetText(); 
     Clipboard.Clear(); 
    } 

    void Form1_GotFocus(object sender, EventArgs e) 
    { 
     Clipboard.SetText(sVal); 
    } 
4

为了给你一个快速的答案,工作中,而不是添加事件处理程序的形式本身,将它们添加到TextBox控制:

textBox1.LostFocus += new EventHandler(Form1_LostFocus); 
textBox1.GotFocus += new EventHandler(Form1_GotFocus); 

如果表单包含任何可见的控件,它永远不会触发GotFocusLostFocus事件。

建议的方式来处理在表单级别此行为是使用:

this.Deactivate += new EventHandler(Form1_LostFocus); 
this.Activated += new EventHandler(Form1_GotFocus); 

textBox1.Leave += new EventHandler(Form1_LostFocus); 
textBox1.Enter += new EventHandler(Form1_GotFocus); 

微软称:

  1. 对于Control.GotFocus Event

    GotFocus和LostFocus事件是与WM_KILLFOCUS和WM_SETFOCUS Windows消息绑定的 的低级别焦点事件。通常, GotFocus和LostFocus事件仅用于更新UICues 或编写自定义控件时。相反,输入和离开事件 应该用于除了使用 激活事件和停用事件的表格类以外的所有控件。

  2. 对于Form.Activated Event

    当应用程序是活动的,并具有多种形式,活性形式 是与输入焦点的形式。不可见的表单不能为 活动表单。激活可见表单的最简单方法是 单击它或使用适当的键盘组合。

  3. 对于Control.Enter Event

    Enter和Leave事件被Form类抑制。 Form类中的 等效事件是激活和停用 事件。

+0

感谢做到了.... – Aravind