0

我以 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?

还有什么好的方法吗?

4

2 回答 2

0

首先,您必须将 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);
    }
}
于 2012-07-12T11:04:01.870 回答
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);
    }
}

我已经测试过它和它的话。如果需要,我可以发送项目

于 2012-07-21T10:18:14.713 回答