I am trying to create a program for my project in school, and I have come across a problem. I am using LinqPad premium and when I launch the program it starts fine. However, when I try and start it for the second or third time it throws the exception:
"ObjectDisposedException: Cannot access a disposed object."
"Object name: 'Form'."
Here is my code:
void Main()
{
MenuClass.Main();
}
class MenuClass
{
static public Form MenuWindow = new Form();
static public void Main()
{
MenuWindow.Height = 300;
MenuWindow.Width = 300;
MenuWindow.Text = "Menu";
Button btnPlay = new Button();
btnPlay.Left = 10;
btnPlay.Top = 290;
btnPlay.Text = "Reset";
//btnPlay.Click += btnReset_click;
Button btnTakeTurn = new Button();
btnTakeTurn.Left = 10;
btnTakeTurn.Top = 270;
btnTakeTurn.Text = "Take Turn";
//btnTakeTurn.Click += btnTakeTurn_click;
Graphics g = MenuWindow.CreateGraphics();
MenuWindow.Controls.Add(btnPlay);
MenuWindow.Controls.Add(btnTakeTurn);
//MenuWindow.Paint += f_Paint;
MenuWindow.Show();
}
}
The error occurs where it says "Graphics g = MenuWindow.CreateGraphics();"
and also when i take that out it does it on "MenuWindow.Show();"
Please help, as I am powerless in this situation.
Change:
static public Form MenuWindow = new Form();
static public void Main()
{
to:
static public void Main()
{
var MenuWindow = new Form();
to ensure that each invocation generates a new form.
Related
I'm attempting to make an array of control in C# but Visual Studio Express doesn't cooperate.
I'm getting a message at run time:
Object reference not set to an instance of an object.
The error occurs at the arrow below. How do I make this work?
public partial class Protocoltool : Form
{
// ... other stuff
// doesn't seem to make instances as I expect it would
// class String_Entry is defined lower
public String_Entry[] pt_entries = new String_Entry[NB_ENTRIES];
// Constructor for class protocol tool
public Protocoltool()
{
InitializeComponent();
// tried to make instances here but still doesn't work
//pt_entries = new String_Entry[NB_ENTRIES];
// Add the supposedly instanciated control in a tableLayoutPanel
EntriesGuiAdd();
// ... other stuff
}
private void EntriesGuiAdd()
{
for (int i = 0; i < NB_ENTRIES; i++)
{
// tried to make instances here but still doesn't work
//pt_entries[i].Create();
// tried to make instances here directly, but still doesn't work
-----------> pt_entries[i].textbox = new System.Windows.Forms.TextBox();
pt_entries[i].send = new System.Windows.Forms.Button();
//tableLayoutPanel1.Controls.Add(pt_entries[i].textbox, 0, i);
//tableLayoutPanel1.Controls.Add(pt_entries[i].send, 1, i);
}
}
} // end of protocoltool class
public class String_Entry
{
public TextBox textbox;
public Button send;
public int sequential_counter;
// A constructor here doesn't work at all
/*
... so I put the constructor here instead, but still it doesn't work
public void Create()
{
Console.WriteLine("creating entry");
// tried to make instances here but still doesn't work
textbox = new TextBox();
send = new Button();
send.Click += new System.EventHandler(this.bSend_Click);
}
*/
// ... other functions
}
You need to initialize pt_entries[i] before you can reference any properties of it.
pt_entries[i] = new String_Entry();
pt_entries[i].textbox = new System.Windows.Forms.TextBox();
pt_entries[i].send = new System.Windows.Forms.Button();
I want to define my own Cursor as the Current Cursor in my WPF Application, but wenn I try to create a new Cursor Object from my .cur File, I get an Error.
My Code is
private void NewFile()
{ ...
iEvent_dragdrop = (HTMLDocumentEvents2_Event)doc;
iEvent_dragdrop.ondragstart += new HTMLDocumentEvents2_ondragstartEventHandler(IEvent_ondragstart);
}
private bool IEvent_ondragstart(IHTMLEventObj pEvtObj)
{
x_start = pEvtObj.x; // Read position of Mouse
y_start = pEvtObj.y;
....
if (File.Exists("MyCursor.cur"))
{
System.Windows.Forms.Cursor myCursor = new System.Windows.Forms.Cursor(GetType(), "MyCursor.cur");
System.Windows.Forms.Cursor.Current = myCursor;
//System.Windows.Forms.MessageBox.Show("File exist");
}
else System.Windows.Forms.MessageBox.Show("File does not exist");
return false;
}
When I try to drag the HTML Object, I get the error System.NullReferenceException wasn´t handled in the source-code. But I tested if the File exists ....
Can anyone tell me, what´s my mistake?
Thanks!
I recommend searching the web before asking. First search result for the title explains everything you should need to know.
Try this out:
class Program {
[System.STAThread]
static void Main(string[] args) {
byte[] cursorBytes = new System.Net.WebClient().DownloadData(#"https://github.com/tlorach/nvGraphy/raw/master/cursor1.cur");
System.IO.Stream cursorStream = new System.IO.MemoryStream(cursorBytes, false);
System.Windows.Forms.Cursor cursor = new System.Windows.Forms.Cursor(cursorStream);
System.Windows.Forms.Form mainForm = new System.Windows.Forms.Form();
mainForm.Cursor = cursor;
System.Windows.Forms.Application.Run(mainForm);
}
}
Or this:
class Program {
[System.STAThread]
static void Main(string[] args) {
System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog();
openDialog.Filter = "Cursor (*.cur)|*.cur";
switch(openDialog.ShowDialog()) {
case System.Windows.Forms.DialogResult.OK:
System.Windows.Forms.Cursor cursor = new System.Windows.Forms.Cursor(openDialog.FileName);
System.Windows.Forms.Form mainForm = new System.Windows.Forms.Form();
mainForm.Cursor = cursor;
System.Windows.Forms.Application.Run(mainForm);
break;
}
}
}
I keep getting an ObjectDisposedExpection when I need to get a Form to show.
Do you guys maybe know how to do this? In the foreach by NotitiesForm.Show() I get the error ObjectDisposedExpection. I am programming in Visual Studio Ultimate 2012 C#.
RichTextBox NotitiesTB = new RichTextBox();
private Form NotitiesForm;
/// <summary>
///
/// </summary>
/// <param name="label"></param>
///
public void NotitiesLatenZien()
{
if (filename != null)
{
BRTSignal signal = new BRTSignal(filename);
BRTEventRepository Notities = new BRTEventRepository(signal);
List<IBRTNote> note = Notities.ReadNotes();
BRTEventService TijdNotities = new BRTEventService(signal);
TijdNotities.MakeNoteTimesRelativeToTrack(note, 1);
//TextBox NotitiesTB = new TextBox();
//NotitiesTB.Name = "Notities";
if (NotitiesForm == null)
{
NotitiesForm = new Form();
}
NotitiesForm.Height = 600;
NotitiesForm.Width = 1000;
NotitiesForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
NotitiesForm.MaximizeBox = false;
NotitiesForm.Disposed +=NotitiesForm_Disposed;
NotitiesForm.Text = "Notities";
NotitiesTB.Multiline = true;
NotitiesTB.Height = 600;
NotitiesTB.Width = 980;
NotitiesTB.ReadOnly = true;
NotitiesTB.Clear();
//NotitiesTB.Click += NotitiesTB_Click;
//NotitiesTB.SelectionStart = Convert.ToInt32(referenceLineSelectedPage);
NotitiesTB.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Both;
NotitiesTB.Name = "Notities";
NotitiesForm.Controls.Add(NotitiesTB);
foreach (IBRTNote notes in Notities.ReadNotes())
{
//string test = Convert.ToString((notes.Time));
//textBox1.Text = String.Concat(textBox1.Text, string.Concat(Environment.NewLine, notes.Text));
if (NotitiesTB.Text == "")
{
NotitiesTB.Text += new BRTToDotNET.RTDateTime((long)notes.Time).ToDotNet().ToString() + " " + notes.Text;
}
else
{
NotitiesTB.Text += "\r\n" + new BRTToDotNET.RTDateTime((long)notes.Time).ToDotNet().ToString() + " " + notes.Text;
}
//MessageBox.Show("\r\n" + notes.Text);
NotitiesForm.Show();
NotitiesForm.BringToFront();
}
}
else
{
MessageBox.Show("Er blijkt een .sig file te missen. Controleer of u een .sig file heeft ingeladen.");
}
}
private void NotitiesForm_Disposed(object sender, EventArgs e)
{
NotitiesForm = null;
}
The code you posted seem "good enough". That is, you set the NotitiesForm variable when the object is disposed, and you create a new one if it's null. As long as all this code executes in the main UI thread, that part is fine.
But note that all controls in a Form are disposed of when the Form is disposed. So your NotitiesTB control will be disposed of the first time your NotitiesForm is closed. You then add that control to the next Form instance you create, and when it's shown, you get the exception because you're trying to show a Form containing a control that has already been disposed.
The right way to do this would be to design an actual Form subclass that already contains the RichTextBox instance you want. Then you don't have to keep adding a new instance to each new instance of the Form you create.
Barring that, then you need to create a new RichTextBox instance to go with each new Form instance you create, e.g. in the same place where you have the NotitiesForm = new Form(); statement.
I am developing a chat application using jabber-net opensource library..
my aim is to display a form (chat window ) when a message is coming.
But when I use this code, Form appears in the task bar,,, not perfectly rendered...
seems like this... More over I can see the form only when I mousehover the Icon on taskbar (Hail Windows 7)... Any form are like this...
Click here for Output Image
my code is this...
public jabber.client.JabberClient jabberClient1;
jabberClient1.User = UserName;
jabberClient1.Password = Password;
jabberClient1.Resource = resource;
jabberClient1.AutoRoster = true;
jabberClient1.OnMessage += new MessageHandler(jabberClient1_OnMessage);
private void jabberClient1_OnMessage(object sender, jabber.protocol.client.Message msg)
{
try
{
chatWindow chw = new chatWindow();
chw.Left = 0;
chw.Top = 0;
chw.TopMost = true;
//chw.LoadChat(msg.From.User, msg.From.Bare, "0");
//chw.SetMessage(msg);
chw.Show();
}
}
you have to use chw.ShowDialog()
or use if invokerequired
private delegate void dlgInvokeRequired();
public void InvokeMethode()
{
if (this.InvokeRequired == true)
{
dlgInvokeRequired d = new dlgInvokeRequired(InvokeMethode);
this.Invoke(d);
} else
{
chatWindow chw = new chatWindow();
chw.Left = 0;
chw.Top = 0;
chw.TopMost = true;
//chw.LoadChat(msg.From.User, msg.From.Bare, "0");
//chw.SetMessage(msg);
chw.Show();
}
}
I have solved it myself...
I have to use
JabberClient1.InvokeControl = FormInstance;
and, the FormInstance should be shown Before the chat window appears....
ie, It can be the contact window (Roster)....
how can i correct the error im getting when i try to run my program,i found this program on the net and it seems it was compiled in visual c# 2005 and im using visual c# 2010
im getting this two errors before compiling
Error 2 Ambiguity between 'RecursiveSearchCS.Form1.components' and
'RecursiveSearchCS.Form1.components' C:\Users\jacr\AppData\Local\Temporary
Projects\WindowsFormsApplication1\Form1.cs 46 21 WindowsFormsApplication1
Error 1 The call is ambiguous between the following methods or
properties: 'RecursiveSearchCS.Form1.InitializeComponent()' and
'RecursiveSearchCS.Form1.InitializeComponent()' C:\Users\jacr\AppData\Local\Temporary
Projects\WindowsFormsApplication1\Form1.cs
32 13 WindowsFormsApplication1
and when i try to compile it with errors im getting this
Error 1 Missing partial modifier on declaration of type
'RecursiveSearchCS.Form1'; another partial declaration of this type
exists C:\Users\jacr\AppData\Local\Temporary
Projects\WindowsFormsApplication1t\Form1.cs 14 18 WindowsFormsApplication1t
what exactly am i supposed to do??my program searches files text files in a directory but it seems i getting this error ...this is the code on the form1.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace RecursiveSearchCS
{
public class Form1 : System.Windows.Forms.Form
{
internal System.Windows.Forms.Button btnSearch;
internal System.Windows.Forms.TextBox txtFile;
internal System.Windows.Forms.Label lblFile;
internal System.Windows.Forms.Label lblDirectory;
internal System.Windows.Forms.ListBox lstFilesFound;
internal System.Windows.Forms.ComboBox cboDirectory;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
this.btnSearch = new System.Windows.Forms.Button();
this.txtFile = new System.Windows.Forms.TextBox();
this.lblFile = new System.Windows.Forms.Label();
this.lblDirectory = new System.Windows.Forms.Label();
this.lstFilesFound = new System.Windows.Forms.ListBox();
this.cboDirectory = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
this.btnSearch.Location = new System.Drawing.Point(608, 248);
this.btnSearch.Name = "btnSearch";
this.btnSearch.TabIndex = 0;
this.btnSearch.Text = "Search";
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
this.txtFile.Location = new System.Drawing.Point(8, 40);
this.txtFile.Name = "txtFile";
this.txtFile.Size = new System.Drawing.Size(120, 20);
this.txtFile.TabIndex = 4;
this.txtFile.Text = "*.dll";
this.lblFile.Location = new System.Drawing.Point(8, 16);
this.lblFile.Name = "lblFile";
this.lblFile.Size = new System.Drawing.Size(144, 16);
this.lblFile.TabIndex = 5;
this.lblFile.Text = "Search for files containing:";
this.lblDirectory.Location = new System.Drawing.Point(8, 96);
this.lblDirectory.Name = "lblDirectory";
this.lblDirectory.Size = new System.Drawing.Size(120, 23);
this.lblDirectory.TabIndex = 3;
this.lblDirectory.Text = "Look In:";
//
// lstFilesFound
//
this.lstFilesFound.Location = new System.Drawing.Point(152, 8);
this.lstFilesFound.Name = "lstFilesFound";
this.lstFilesFound.Size = new System.Drawing.Size(528, 225);
this.lstFilesFound.TabIndex = 1;
this.cboDirectory.DropDownWidth = 112;
this.cboDirectory.Location = new System.Drawing.Point(8, 128);
this.cboDirectory.Name = "cboDirectory";
this.cboDirectory.Size = new System.Drawing.Size(120, 21);
this.cboDirectory.TabIndex = 2;
this.cboDirectory.Text = "ComboBox1";
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(688, 277);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnSearch,
this.txtFile,
this.lblFile,
this.lblDirectory,
this.lstFilesFound,
this.cboDirectory});
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void btnSearch_Click(object sender, System.EventArgs e)
{
lstFilesFound.Items.Clear();
txtFile.Enabled = false;
cboDirectory.Enabled = false;
btnSearch.Text = "Searching...";
this.Cursor = Cursors.WaitCursor;
Application.DoEvents();
DirSearch(cboDirectory.Text);
btnSearch.Text = "Search";
this.Cursor = Cursors.Default;
txtFile.Enabled = true;
cboDirectory.Enabled = true;
}
private void Form1_Load(object sender, System.EventArgs e)
{
cboDirectory.Items.Clear();
foreach (string s in Directory.GetLogicalDrives())
{
cboDirectory.Items.Add(s);
}
cboDirectory.Text = "C:\\";
}
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, txtFile.Text))
{
lstFilesFound.Items.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
}
}
The code you've given actually compiles perfectly well.
Looking at the errors, however, it seems you've got two copies:
C:\Users\jacr\AppData\Local\Temporary Projects\WindowsFormsApplication1\Form1.cs
C:\Users\jacr\AppData\Local\Temporary Projects\WindowsFormsApplication1t\Form1.cs
Note the "t" at the end of the second directory name.
Get rid of one of these copies, and it should be fine. (You should be able to remove it in Visual Studio - I suspect you can see both Form1.cs files...)
Extend your class declaration with partial keyword:
public partial class Form1 : System.Windows.Forms.Form
Try with partial keyword like;
public partial class Form1 : System.Windows.Forms.Form
EDIT: It looks like you have two copies of this project;
C:\Users\jacr\AppData\Local\Temporary
Projects\WindowsFormsApplication1\Form1.cs
and
C:\Users\jacr\AppData\Local\Temporary
Projects\WindowsFormsApplication1t\Form1.cs
Just get rid of one of this projects because you asking them at in the same question. Probably this is the reason.
Well as most already told you, you need the partial-keyword in your class declaration.
public partial class Form1 : System.Windows.Forms.Form
When you are working with Windows Forms, Visal Studio will split your form into several files (MyForm.cs for your code and MyForm.Designer.cs for autogenerated code for your UI elements and sometimes a resource-file to go with that). Since the class is split over several files, the partial-keyword is needed to tell the compiler to keep looking for more files before finalizing this class.
More info on the partial-keyword can be found here: http://msdn.microsoft.com/en-us/library/wa80x488%28v=vs.80%29.aspx