从另一个类声明一个方法
本文关键字:一个 方法 另一个 声明 | 更新日期: 2023-09-27 18:03:33
下面是我遇到的问题,特别是有**围绕它。当我的ImageViewer打开时,我想调用方法"toolStripButton1_Click()"。目前,当ImageViewer打开时,所选的图像并没有随之打开。我已经公开了这个方法,希望它能解决问题,但我没有。
public partial class MediaPlayer : Form
{
public ImageViewer iv;
public AudioPlayer ap;
public VideoPlayer vp;
public MediaPlayer()
{
InitializeComponent();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (ofdSelectMedia.ShowDialog() == DialogResult.OK)
switch(ofdSelectMedia.FilterIndex){
**case 1: new ImageViewer().Show(); public void toolStripButton1_Click(object sender, EventArgs e);**
break;
case 2: new AudioPlayer().Show();
break;
case 3: new VideoPlayer().Show();
break;
}
}
}
谢谢。
试试这个…
public void toolStripButton1_Click(object sender, EventArgs e)
{
somemethod();
}
void somemethod()
{
//your code which u want to execute on click of a button
}
在case1中调用方法somemethod();
而不是调用事件
将代码从toolStripButton1_Click方法移动到一个函数中,并从case子句和toolStripButton1_Click处理程序调用它。
private void DoIt()
{
// The code from the toolStripButton1_Click handler
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
DoIt();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (ofdSelectMedia.ShowDialog() == DialogResult.OK)
switch(ofdSelectMedia.FilterIndex){
case 1: new ImageViewer().Show();
DoIt();
break;
case 2: new AudioPlayer().Show();
break;
case 3: new VideoPlayer().Show();
break;
}
}
你所做的是一个方法声明,而不是一个方法调用。试着
switch(ofdSelectMedia.FilterIndex){
case 1: new ImageViewer().Show();
toolStripButton1_Click(sender, e);
break;
case 2: new AudioPlayer().Show();
break;
case 3: new VideoPlayer().Show();
break;
}
使用如下所示的PerformClick()
public partial class MediaPlayer : Form
{
public ImageViewer iv;
public AudioPlayer ap;
public VideoPlayer vp;
public MediaPlayer()
{
InitializeComponent();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (ofdSelectMedia.ShowDialog() == DialogResult.OK)
switch(ofdSelectMedia.FilterIndex){
case 1:
new ImageViewer().Show();
toolStripButton1.PerformClick();
break;
case 2: new AudioPlayer().Show();
break;
case 3: new VideoPlayer().Show();
break;
}
}
它听起来像你想做的事情:
case 1:
var imgViewer = new ImageViewer();
imgViewer.Show();
imgViewer.toolStripButton1_Click(sender, e);
break;
虽然我个人认为,我会重构ImageViewer
,让它有一个ShowImage
方法,或者类似的,所以它变成:
case 1:
var imgViewer = new ImageViewer()
imgViewer.Show();
imgViewer.ShowImage();
break;
和你的ImageViewer
有:
public void ShowImage() {...}
void openToolStripMenuItem_Click(object sender, EventArgs e) {
ShowImage();
}