简体   繁体   中英

Tooltip attached to mouse in C#

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 = ".....";

提示

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.

  1. P/Invoke the SendMessage function. Set the hwnd to your target window and pass in a TTM_ADDTOOL message 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.

  2. Apparently you can use the CreateWindowEx() function with TOOLTIPS_CLASS as 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM