从另一个表单调用MouseEventHandler

时间:2012-07-12 10:40:00

标签: c# winforms

我以Main格式创建一个MouseEventHandler:

        public Home()
        {
            InitializeComponent();

            this.KeyPreview = true;
            this.MouseMove += new MouseEventHandler(Home_MouseMove);
        }

        public static void Home_MouseMove(object sender, MouseEventArgs e)
        {
            bomb.Stop();
            bomb.Start();
        }

如何从其他表单调用MouseEventHandler?

还有其他好方法吗?

2 个答案:

答案 0 :(得分:0)

Fisrt你必须将Home_MouseMove事件更改为非静态事件:

public void Home_MouseMove(object sender, MouseEventArgs e)
    {
        bomb.Stop();
        bomb.Start();
    }

转到program.cs文件并更改以下代码:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new FrmMain());
    }
}

到此代码:

static class Program
{
    public static FrmMain MainForm;// add this line
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        MainForm = new FrmMain();// add this line
        Application.Run(MainForm);
    }
}

现在在form2上你可以像这样在主窗体中调用MouseMove:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();   
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // call MouseMove event in main form
        Program.MainForm.FrmMain_MouseMove(null, null);
    }
}

答案 1 :(得分:0)

我已经测试过了。有用。 主要形式的代码是:

public partial class FrmMain : Form
{
    public FrmMain()
    {
        InitializeComponent();
    }

    public void FrmMain_MouseMove(object sender, MouseEventArgs e)
    {
        this.label1.Text = DateTime.Now.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        new Form1().Show();
    }
}

Form1代码是:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Program.MainForm.FrmMain_MouseMove(null, null);
    }
}

它有一个带有点击事件的按钮。单击该按钮时,将显示主窗体中的鼠标移动事件

最后,program.cs代码是

static class Program
{
    public static FrmMain MainForm;
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        MainForm = new FrmMain();
        Application.Run(MainForm);
    }
}

我测试了它和它的话。如果你愿意,我可以发送项目