Hey, I would like to call a few functions from a static method, but it seems I can't.

More specifically, I would like to start or stop a timer from a static hook, called when you click your left mouse button.

Here is the code

//When you click...
    public static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 &&
            MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
        {
            MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
            if(bool1 == true){
            	if(checkBox1.Checked == true){
				timer1.Start();
				}
            }
        }
    	if (nCode >= 0 &&
            MouseMessages.WM_LBUTTONUP == (MouseMessages)wParam)
        {
            MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
            if(bool1 == true){
            	if(checkBox1.Checked == true){
				timer1.Stop();
				}
            }
        }
    	
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

The timer, checkbox and bool are all trying to be called but can't be since the method is static.

Could I change the method to be non-static? Because I've tried that, and it requires an object refrence, and when I put 'object sender' in it, it throws another error etc.

Please tell me if there is a way of doing this!

Recommended Answers

All 3 Replies

Put a static timer field in the class and when the form is created set the static reference to the instance reference .. they will have the same reference but that way you can see it from a static method.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace daniweb
{
  public partial class frmStatic : Form
  {
    internal static Timer FormTimer { get; set; }

    public frmStatic()
    {
      InitializeComponent();
      FormTimer = this.timer1;
    }

    public static void SomeHook()
    {
      FormTimer.Enabled = true;
    }
  }
}

Must I declare both timer1 and FormTimer?

Nevermind, I got it to work.

:)

Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.