根据documentation,您应该在将图像从一种形式传递给另一种形式时创建图像的克隆。喜欢的东西:
frmAdd.pctImage.Image = pctImage.Image.Clone() as Image;
编辑:作为lumberjack4指出的那样,你还可以创建一个新的,看不见的frmAdd
和图像分配给这种形式,而不是已经所示。图像可能实际上被正确分配(尽管您仍然应该克隆它),但它永远不会在屏幕上显示,因为您的本地frmAdd
从不显示。下面是一些代码,会告诉你如何做到这一点:
在frmAdd
---------:
public partial class frmAdd : Form
{
// Stores a reference to the currently shown frmAdd instance.
private static frmAdd s_oInstance = null;
// Returns the reference to the currently shown frmAdd instance
// or null if frmAdd is not shown. Static, so other forms can
// access this, even when an instance is not available.
public static frmAdd Instance
{
get
{
return (s_oInstance);
}
}
public frmAdd()
{
InitializeComponent();
}
// Sets the specified picture. This is necessary because picAdd
// is private and it's not a good idea to make it public.
public void SetPicture (Image oImage)
{
picAdd.Image = oImage;
}
// These event handlers are used to track if an frmAdd instance
// is available. If yes, they update the private static reference
// so that the instance is available to other forms.
private void frmAdd_Load (object sender, EventArgs e)
{
// Form is loaded (not necessarily visible).
s_oInstance = this;
}
private void frmAdd_FormClosed (object sender, FormClosedEventArgs e)
{
// Form has been closed.
s_oInstance = null;
}
// Whatever other code you need
}
在frmNew ---------:
public partial class frmNew : Form
{
public frmNew()
{
InitializeComponent();
}
private void btnCancel_Click (object sender, EventArgs e)
{
// Is there an active instance of frmAdd? If yes,
// call SetPicture() with a copy of the image used by
// this frmNew.
frmAdd oFrm = frmAdd.Instance;
if (oFrm != null)
oFrm.SetPicture (picNew.Image.Clone() as Image);
}
}
有2 PictureBox
涉及对照:picAdd
在frmAdd
和picNew
在frmNew
。当点击btnCancel
时,frmNew
中的代码将检查是否存在有效的frmAdd
实例,如果是,则设置其图像。
请注意picAdd
不是公共控件 - 它应该是私人的。将控件设置为公开形式并不是一个好主意,因为它允许不受控制地访问它们,并且表单不会确切地知道它们的状态(因为其他人可能会在没有表单知道的情况下更改这些控件)。这可能导致变化很难在更大的程序中修复错误。
如果您需要访问其窗体之外的控件,请将控件保留为私有,并在需要时更新控件的形式中创建公共属性/方法 - 如上面的SetPicture
方法。这仍然可以让你从表单之外分配图片,但是表单控制了这种情况的发生,因为SetPicture
可以验证图像等。如果你只是将你的控件设置为公开,这是不可能的。
仍然没有工作... :( 我已经试过这个。 –
当你发生什么事情 尝试这个?你有没有发现异常或者什么都没有显示? – xxbbcc
只是没有显示.. –