How to set tooltip at current mouse location?

2020-07-22 19:48发布

问题:

I registered Hotkey: Ctrl + Space. Hotkey message is sent to:

private void Hotkey_press()
{
... // I want to show tooltip "Hello" at current mouse location.
}

Is there any way to show this tooltip even the mouse doesnt point to any control and it is outside my Window.Form1?

Edit: That ToolTip can show even the form lost focus or hide

回答1:

You want something like

ToolTip tt = new ToolTip();
IWin32Window win = this;
tt.Show("String", win, mousePosition);

Where the MousePosition can be obtained from the MouseEventArgs via

private SomeMouseEventHandler(object sender, MouseEventArgs e)
{
    System.Drawing.Point mousePosition = e.Location;
    ...
}

or using

System.Drawing.Point mousePosition = Cursor.Position;

also, you may want to set a longer duration for which the ToolTip is displayed, well just use the overloads available for the Show method, tt.Show("String", win, mousePosition, 5000); will display the tool tip for 5 seconds.

I hope this helps.



回答2:

Tooltip tip = new ToolTip();
tip.ShowAlways = true;
tip.Show("My tooltip",this,Cursor.Position.X,Cursor.Position.Y);

http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.tooltip.showalways.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.aspx



回答3:

As this answer suggests, there is no managed way to accomplish this. If you want to show a tool tip control when your program is not in focus then the "right" way to do it is to PInvoke Win32 and use CreateWindowEx. The answer linked above given by gideon shows some pointers on how to do it, but nonetheless it is very complicated.

If you don't mind using thrid party libraries, AutoIt provides a way to create tool tips easily without having to deal with Win32 yourself.

Here is a very simple example demonstrating use:

//make sure AutoItX3.dll is referenced in your project
using AutoItX3Lib;

private AutoItX3 myAutoIt = new AutoItX3();

private async void ShowToolTipAtMouse(string message)
{
    //default position is bottom right of mouse pointer,
    //but you can set the x and y positions yourself
    myAutoIt.ToolTip(message);

    //call the function again with an empty argument to close
    await Task.Delay(1000);
    myAutoIt.ToolTip(String.Empty);
}

This will work as long as your program is running; doesn't matter if it is in/out of focus or even hidden. Downside is you don't get the regular fade out animation (it just vanishes). Also, if you need multiple tool tips at once you need to have multiple AutoItX3 objects.