'C# Forms application crashes after I re-open a secondary form
I'm having this issue with my C# Forms application. I loaded an Hebrew font into the app and I noticed it crashes the program when I re-open a form using a button.
InitializeComponent();
InitCustomLabelFont();
private void InitCustomLabelFont()
{
//Create your private font collection object
PrivateFontCollection pfc = new PrivateFontCollection();
//Select your font from the resources.
int fontLength = Properties.Resources.SecularOne_Regular.Length;
// create a buffer to read in to
byte[] fontdata = Properties.Resources.SecularOne_Regular;
// create an unsafe memory block for the font data
System.IntPtr data = Marshal.AllocCoTaskMem(fontLength);
// copy the bytes to the unsafe memory block
Marshal.Copy(fontdata, 0, data, fontLength);
// pass the font to the font collection
pfc.AddMemoryFont(data, fontLength);
// using the font...
headerLbl.Font = new Font(pfc.Families[0], 20);
loginBtn.Font = new Font(pfc.Families[0], 18);
...
...
}
I have this InitCustomLabelFont() function on Form1 and Form2. Form1 has a button that opens Form2. I noticed that when I re-open Form2 after I closed it I get a:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt
Does anyone has an idea why my app crashes?
*** EDIT ***
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); //this is where it crashes
}
}
Solution 1:[1]
Thanks everybody it works now!
the thing was:
private void RegisterForm_FormClosing(Object sender, FormClosingEventArgs e)
{
pfc.Dispose();
}
while putting
private PrivateFontCollection pfc = new PrivateFontCollection();
above the public Form1()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
