如何在子表单中启用快捷方式

时间:2011-03-17 02:48:56

标签: c# .net

我已经编写了一个框架应用程序,它是一个Windows窗体应用程序作为父窗体。当它启动时,它会在/ modules中找到dll并将它们作为扩展加载。当我单击父窗体中的menuItem时,特定的dll将工作。如果dll是一个Form应用程序,它将显示。但是当我尝试使用快捷方式时(只有内置插件,例如:CTRL-C ... )在childForm中,热键不起作用。有人告诉我为什么以及如何解决这个问题?这是我的代码:

//parent.exe--ModuleEntrance.cs
public abstract class ModuleEntrance {
  public abstract string[] GetMenuNames();
  public abstract string[] GetMenuItemNames();
  public abstract EventHandler[] GetEventHandlers();
}
//parent.exe--ParentForm.cs
public partial class MDIParent : Form {
  public MDIParent() { //CTOR
    InitializeComponent();
    ModuleEntrance oneEntrance;
    string oneMenuName, oneMenuItemName;
    ToolStripMenuItem theMenu, theMenuItem;
    for(){ //iterate dlls in /modules, if it implement ModuleEntrance, load it. 
          //And 1)load menu&menuItem.  
          //2) connect handler to menuItem.click through 
        //<code:theMenuItem.Click += new EventHandler(oneEntrance.GetEventHandlers()[i]);>
    }
}

//--------------
//child.dll-- EntranceImp.cs  //implement AC
public class EntranceImp : ModuleEntrance {
  public override string[] GetMenuNames() {
    return new string[] { "MENU"};
  }
  public override string[] GetMenuItemNames() {
    return new string[] { "OpenChildForm"};
  }
  public override EventHandler[] GetEventHandlers() {
    return new EventHandler[]{
      (EventHandler)delegate(object sender, EventArgs e) { //Anonymous method
        childForm form = new childForm();
        //find MDIparent and connect them
        ToolStripMenuItem mi = (ToolStripMenuItem)sender;
        form.MdiParent = (Form)(mi.OwnerItem.Owner.Parent);  //It works!
        form.Show();
      }
    };
  }
}
//child.dll--childForm.dll
//...

1 个答案:

答案 0 :(得分:0)

子表单必须以某种方式通知父表单关于关键事件。

执行此操作的方法是让子窗体显示父窗体可以侦听的按键事件。每次更改子表单时,请记住删除父事件处理程序,否则最终会导致内存泄漏,因为在释放对它们的所有引用(包括事件处理程序)之前,对象不会被垃圾回收。

class Parent
{
    KeyEventHandler KeyDownHandler;

    public Parent()
    {
        KeyDownHandler = new KeyEventHandler(form_TextBoxKeyDown);
    }

    void SetChildForm(Child form)
    {
        form.TextBoxKeyDown += KeyDownHandler;
    }

    void RemoveChildForm(Child form)
    {
        form.TextBoxKeyDown -= KeyDownHandler;
    }

    void form_TextBoxKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control)
        {
            switch (e.KeyCode)
            {
                case Keys.C:

                    break;
                case Keys.X:

                    break;
                case Keys.V:

                    break;
            }
        }
    }
}

class Child
{
    TextBox txtBox;

    public event KeyEventHandler TextBoxKeyDown;

    internal Child()
    {
        txtBox.KeyDown += new KeyEventHandler(txtBox_KeyDown);
    }

    void txtBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (TextBoxKeyDown != null)
            TextBoxKeyDown(sender, e);
    }
}