简体   繁体   中英

How can I use an Image List to draw C# dragging outside of my own windows

I am using C#'s inbuilt drag and drop via Control.DoDragDrop(). I use an Image List and ImageList_DragMove and friends to move a semi-transparent image around, tracking with the mouse. (See my reply in this thread for more information). How can I make the ImageList track the mouse when it is outside my windows? I only receive mouse position messages in OnDragOver(), and only when the mouse is over one of my Windows. The drag is going to another instance of my application, and I would like the ImageList to go the whole way, including over the desktop. I guess the basic problem is that DoDragDrop runs its own little message loop.

Windows Explorer gets this done so I know it is possible. I suppose I could start a thread to keep track of the mouse or write my own drag/drop message loop, but I am hoping for an easier way.

You cannot draw outside your own windows. The way to do this is by changing the mouse cursor. That's what the GiveFeedback event is available, set e.UseDefaultCursors to false and set the Cursor.Current.

Just to give you an idea what this looks like, here's a sample form that drags visible text. Alter it to draw the bitmap the way you want it, from your ImageList for example. Beware that Bitmap.GetHicon() does not create great icons, the color mapping is poor.

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.GiveFeedback += Form1_GiveFeedback;
    }

    void Form1_GiveFeedback(object sender, GiveFeedbackEventArgs e) {
        string txt = "Dragging text";
        SizeF sz;
        using (var gr = this.CreateGraphics()) {
            sz = gr.MeasureString(txt, this.Font);
        }
        using (var bmp = new Bitmap((int)sz.Width, (int)sz.Height)) {
            using (var gr = Graphics.FromImage(bmp)) {
                gr.Clear(Color.White);
                gr.DrawString(txt, this.Font, Brushes.Black, 0, 0);
            }
            bmp.MakeTransparent(Color.White);
            e.UseDefaultCursors = false;
            IntPtr hIcon = bmp.GetHicon();
            Cursor.Current = new Cursor(hIcon);
            DestroyIcon(hIcon);
        }
    }
    protected override void OnMouseDown(MouseEventArgs e) {
        this.DoDragDrop("example", DragDropEffects.Copy);
    }
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    extern static bool DestroyIcon(IntPtr handle);

}

I suggest that you create a special form and drag it instead of using an ImageList. We have done this in our products (for example, XtraGrid) to allow the end-user arrange columns.

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