0

I am using custom font and if I want to change label's text it causes: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt" How can I fix that ?

    private void LoadFont()
    {
        PrivateFontCollection pfc = new PrivateFontCollection();
        int fontLength = Resources.Nexa_Regular.Length;
        byte[] fontdata = Resources.Nexa_Regular;
        System.IntPtr data = Marshal.AllocCoTaskMem(fontLength);
        Marshal.Copy(fontdata, 0, data, fontLength);
        pfc.AddMemoryFont(data, fontLength);
        lblStatus.Font = new Font(pfc.Families[0], lblStatus.Font.Size);
        Marshal.FreeCoTaskMem(data);
        pfc.Dispose();
    }
    private void MainForm_Load(object sender, EventArgs e)
    {
        LoadFont();
    }
    private void SetStatus()
    {
        if (IsActive())
        {
            lblStatus.Text = "Active"; // Error: Attempted to read or write protected memory. This is often an indication that other memory is corrupt
            lblStatus.ForeColor = Color.Green;
        }
        else
        {
            lblStatus.Text = "Not Active";
            lblStatus.ForeColor = Color.Red;
        }
    }
dfsvs
  • 27
  • 8
  • 1
    Why do you dispose the `PrivateFontCollection` ? Make `pfc` a class level variable and dispose it when you close the Form. The font should be alive as long as a control is using it. –  Jun 17 '20 at 15:20
  • Actually at the beginning I wasn't using dispose but then I added to fix but didn't work :( But without it or with it doesnt matter same error appears – dfsvs Jun 17 '20 at 15:29
  • See the snippets and the comments [here](https://stackoverflow.com/q/15949057/10216583). –  Jun 17 '20 at 15:40
  • 1
    Preserve your `PrivateFontCollection` and **don't** call `Marshal.FreeCoTaskMem(data);` (you'll corrupt the Font data still in use). See the (last three) methods [here](https://stackoverflow.com/a/57231407/7444103). You need to preserve the collection of Fonts until any of these are in use. Dispose of the `PrivateFontCollection` when the Form that uses it is closed (`FormClosed `event). Also, use/assign Fonts added to your `PrivateFontCollection` only after you have filled it. – Jimi Jun 17 '20 at 17:35
  • I changed UseCompatibleTextRendering to false and it works now. Too weird. – dfsvs Jun 17 '20 at 17:50
  • Jimi thanks I am gonna try – dfsvs Jun 17 '20 at 17:58

0 Answers0