Search code examples
c#winformsleap-motion

Listener lost when window is not in focus C#


I have this listener

public class LeapEventListener : Listener
{
    public string frame = string.Empty;
    public string Frame { get { return frame; } }
    public event EventHandler FrameChanged;

    private void SetFrame(string value)
    {
        if (value == null) value = string.Empty;
        if (frame == value) return;
        frame = value;
        var handler = FrameChanged;
        if (handler != null) handler(this, EventArgs.Empty);

    }
    public override void OnFrame (Controller controller)
    {
         Frame frame = controller.Frame();
         FingerList fingers = frame.Fingers;

        SetFrame("Frame id: " + frame.Id); 
    }

    public override void OnInit (Controller controller)
    {
        Console.WriteLine ("Initialized");
    }

    public override void OnConnect (Controller controller)
    {
        Console.WriteLine ("Connected");
        //If using gestures, enable them:
        controller.EnableGesture (Gesture.GestureType.TYPE_CIRCLE);
    }

    //Not dispatched when running in debugger
    public override void OnDisconnect (Controller controller)
    {
        Console.WriteLine ("Disconnected");
    }
}

Then global in my Form1.cs

Controller controller = new Controller();
LeapEventListener listener = new LeapEventListener();

and in public Form1()

string fingers = listener.frame;
controller.AddListener(listener);
label1.DataBindings.Add("Text", listener, "Frame");

All is working fine until I leave focus from the window. Label text is not changing anymore if I leave focus, then wen I come back on the window with focus the label text start changing with information from listener.

Why listener is not working when I don't have the window in focus?


Solution

  • The Leap API has a concept of foreground and background application. By default, only the foreground application receives tracking data. This is to prevent your application from receiving input when the user is interacting with some other application.

    If you really want frames when in the background -- and are sure it won't cause problems -- you can request the background frames policy: Foreground and Background Applications.

    Enabling this policy will get frames when another non-Leap application has focus. If you need frames when a Leap-enabled application, there is a an undocumented policy flag you can use (1 << 15).