问题
How do I get a tooltip that is attached to the mouse cursor using C#? I'm trying to achieve an effect like the following, a small tooltip showing the status of Ctrl / Shift / Alt keys.
I'm currently using a Tooltip but it refuses to display unless it has about 2 lines of text.
tt = new ToolTip();
tt.AutomaticDelay = 0;
tt.ShowAlways = true;
tt.SetToolTip(this, " ");
In mouse move:
tt.ToolTipTitle = ".....";
回答1:
So I don't think there is any way you could do this purely with managed code. You would have to go native.
The way I see it there are two options.
P/Invoke the SendMessage function. Set the
hwndto your target window and pass in aTTM_ADDTOOLmessage and a TOOLINFO structure for the lParam. This is useful when you want a tooltip on an external window you haven't created (one that isn't in your app). You could get its hwnd by calling FindWindow.See how all this is done here in this article. You just have to add the P/Invoke.
Apparently you can use the
CreateWindowEx()function withTOOLTIPS_CLASSas a classname and it will generate a tooltip for you. Something like this:HWND hwndTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwndParent, NULL, hinstMyDll, NULL); SetWindowPos(hwndTip, HWND_TOPMOST,0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);See the whole article here: http://msdn.microsoft.com/en-us/library/windows/desktop/bb760250(v=vs.85).aspx
To get you upto speed, you would have something like this defined in you .NET code. I got the definition from here.
You will find all the structures I've mentioned in my answer on the same website (or other similar ones) Once you have defined all of them in your code, you can then easily transpose/port the C samples that are in my answer and the linked articles.:
class NativeFunctions
{
[DllImport("user32.dll", SetLastError=true)]
static extern IntPtr CreateWindowEx(
WindowStylesEx dwExStyle,
string lpClassName,
string lpWindowName,
WindowStyles dwStyle,
int x,
int y,
int nWidth,
int nHeight,
IntPtr hWndParent,
IntPtr hMenu,
IntPtr hInstance,
IntPtr lpParam);
}
来源:https://stackoverflow.com/questions/11098468/tooltip-attached-to-mouse-in-c-sharp