2016-01-16 22 views
0

它已被问了几次,但我不能使用任何答案。 我的问题是,每次我想改变轨迹条的值都会保持专注,即使我点击窗口的其他部分。当我想要使用这些键时,他们只是在trackbarbox中工作。Trackbar一直在偷我的注意力

我是怎么试试?:

-I试图设置CausesValidation/TabStop/Topmostfalse/true

-I试图用MouseLeave/FocusEnter事件来设置焦点回到我的形式与this.Focus()

-I试图把

protected override bool IsInputKey(Keys keyData) 
{ 
    return true; 
} 

和/或

protected override bool ShowWithoutActivation 
{ 
    get { return true; } 
} 

到Maincode

这里PROGRAMM的截图来了解我的问题: It's german but that doesn't matter. I want to press Enter while I'm drawing the line but the trackbar keeps focused and blocks it

+1

将焦点设置为别的东西?你无法专注表格 - 没有什么可以关注的。您可以将屏幕外的文本框作为最后的手段。 – SimpleVar

+0

但我必须对我的Form Keypress事件做出反应 – bravobyte

+0

在客户端From区域(也有此keypress事件的地方)使用'mouse-down/click'事件,在该事件处理程序中移除焦点或设置为专注于另一种控制。 – Stefan

回答

0

通常的方法是设置KeyPreview = true后覆盖OnKeyDown事件:

protected override void OnKeyDown(KeyEventArgs e) 
    { 
     base.OnKeyDown(e); 
     // your code here.. 
     Text = "Testing: KeyCode" + e.KeyCode; 
    } 

但是你也可以使用PreviewKeyDown事件。确保将表格的KeyPreview属性设置为true,并将一个公共事件添加到可能窃取/接收焦点的所有控件!

由于控制的PreviewKeyDown事件usees需要路由事件到窗体的KeyDown事件不同的说法:

private void CommonPreviewKeyDown(object sender, PreviewKeyDownEventArgs e) 
    { 
     Form1_KeyDown(this, new KeyEventArgs(e.KeyCode)); 
    } 



    private void Form1_KeyDown(object sender, KeyEventArgs e) 
    { 
     // your code here.. 
     Text = "Testing: KeyCode" + e.KeyCode; 
    } 

你可能想挂钩手柄代码:

void routeKeys(Control container) 
    { 
     foreach (Control ctl in container.Controls) 
      if (ctl.CanFocus) ctl.PreviewKeyDown += CommonPreviewKeyDown; 

    } 

这样称呼它:

public Form1() 
    { 
     InitializeComponent(); 
     routeKeys(this); 
    } 

当然您可能要添加过滤器,以防止你的表格是不会处理按键的路由..

的区别这两种技术之间是当你覆盖Form.OnKeyDown你会从任何地方获得的KeyEvents;这将包括例如文本框中您的角色和编辑键都被路由到表单。

如果你不想,你需要一个过滤器添加到事件:

if (tb_notes.Focused) return; 
if (tb_moreNotes.Focused) return; 
if (rtb_edit.Focused) return; 

第二种方式让我们决定哪些控制应包括或排除在路由..:

if (ctl.CanFocus && !(ctl is TextBox || ctl is RichTextBox))    
    ctl.PreviewKeyDown += CommonPreviewKeyDown; 
+0

好吧,那么容易,然后我想..我只是不得不改变KeyPreview ..谢谢yooou – bravobyte