views:

320

answers:

3

When I clicked on a control,

How to get cursor position relative to upper left corner of a (winforms) control ?

C#, VS 2005

PS: I'm asking on context of tooltip "show" method which need that coordinates ..

+1  A: 

This is my code to set tooltips on a composite control, might give you a clue (LED derivers from UserControl):

    public LED()
    {
        InitializeComponent();
        m_Image = global::AdvAdmittance.Controls.Properties.Resources.ledgray_small;
        m_ToolTip = new ToolTip();
        m_ToolTip.AutoPopDelay = 5000;
        m_ToolTip.InitialDelay = 1000;
        m_ToolTip.ReshowDelay = 500;
        m_ToolTip.ShowAlways = true;
        m_LedPictureBox.MouseHover += new EventHandler(m_LedPictureBox_MouseHover);
        m_LedPictureBox.MouseLeave += new EventHandler(m_LedPictureBox_MouseLeave);
        m_LedPictureBox.Click += new EventHandler(m_LedPictureBox_Click);
    }

    void m_LedPictureBox_MouseHover(object sender, EventArgs e)
    {
        if (m_ToolTipText != string.Empty)
        {
            Point toolTipPoint = this.Parent.PointToClient(Cursor.Position);
            toolTipPoint.Y -= 20;
            m_ToolTip.Show(m_ToolTipText, this.Parent, toolTipPoint);
        }
    }

    void m_LedPictureBox_MouseLeave(object sender, EventArgs e)
    {
        m_ToolTip.Hide(this.m_LedPictureBox);
    }
Bolek Tekielski
A: 

Ahh, Thanks for an answer.

All I need is a PointToClient method.

I hope (maybe) it will be useful for other people, here "my" code.

I took almost all code from http://support.microsoft.com/kb/322634 and modified three lines:

   void treeView1_MouseMove(object sender, MouseEventArgs e)
    {
        // Get the node at the current mouse pointer location.
        TreeNode theNode = this.treeView1.GetNodeAt(e.X, e.Y);

        // Set a ToolTip only if the mouse pointer is actually paused on a node.
        if ((theNode != null))
        {
            // Verify that the tag property is not "null".
            if (theNode.Tag != null)
            {
                // Change the ToolTip only if the pointer moved to a new node.
                if (theNode.Tag.ToString() != this.toolTip1.GetToolTip(this.treeView1))
                {
                    //this.toolTip1.SetToolTip(this.treeView1, theNode.Tag.ToString());
                    Point c = System.Windows.Forms.Cursor.Position;
                    Point p = treeView1.PointToClient(c);
                    this.toolTip1.Show(theNode.Tag.ToString(), treeView1, p);
                }
            }
            else
            {
                this.toolTip1.SetToolTip(this.treeView1, "");
            }
        }
        else     // Pointer is not over a node so clear the ToolTip.
        {
            this.toolTip1.SetToolTip(this.treeView1, "");
        }
    }
Alexander Stalt