1

I'm struggling with an issue I can't get round with. I'm building an application which generates a wave with a adjustable frequency.

As this wave need to be heard constantly I use the Application.Idle method with some code. When I run the application in Debug mode it runs fine. In Release mode however it crashes with a "System.NullReferenceException" error. I googled around and found that this can be solved with unchecking Project Properties=>Build=>Optimize code.

So far, so good

However when I run the executable it crashes again with the"System.NullReferenceException" error.

I believe my problem is different as the question it would duplicate. as said I can run the program in Visual Studio both in Debug and Release mode without any issue, but onces it has been build the .exe crashes. So debugging doesn't make it clearer

Below code is a simple code to demonstrate the Application Idle

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Xna.Framework;
using System.Runtime.InteropServices;

namespace PeekMessageTest
{
    public partial class Form1 : Form
    {

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("User32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool PeekMessage(
        ref Message msg,
        IntPtr hWnd,
        uint messageFilterMin,
        uint messageFilterMax,
        uint flats);

        const float SampleRate = 44100;

        public Form1()
        {
            InitializeComponent();
            textBox1.Text = "0";
            Application.Idle += new EventHandler(Application_Idle);
        }

        void Application_Idle(object sender, EventArgs e)
        {
            Message msg = new Message();
            while (!PeekMessage(ref msg, IntPtr.Zero, 0, 0, 0))
            {
                Thread.Sleep(10);
                textBox1.Text = (Convert.ToDouble(textBox1.Text) + 1).ToString();
            }
        }
    }
}

I've create just a form with a counter which is updated. As said the .exe crashes in the "Application_Idle".

Can someone help me with this please?

Many thx

HB1963
  • 107
  • 1
  • 2
  • 11
  • I have confirmed the code sample provided can be run and the problem can be duplicated. I am voting to reopen. – NightOwl888 Feb 16 '18 at 19:24
  • The winforms Message structure does not match the native MSG structure. It is too small, the pinvoke call corrupts the stack content and that can all kind of random misery. Use the [correct declaration](http://www.pinvoke.net/default.aspx/user32/PeekMessage.html). – Hans Passant Feb 16 '18 at 19:48
  • @Hans Passant, thx. This fixed it!!! – HB1963 Feb 16 '18 at 23:30

0 Answers0