突出显示c#中动态控制的潜在位置

时间:2015-11-03 06:54:15

标签: c# .net winforms

我创建了一个应用程序,用户可以在运行时拖放控件。我使用我的ss函数将表格中的控件与使用2D数组的方式对齐。我希望应用程序显示/突出控件在接近某个坐标时所处的位置。

struct IconPanel
{
    public int left;
    public int top;
}

static void ss(Control control)
{
    int row, col, nearestCol = 0, nearestRow = 0, rowDist = 100, diff, colDist = 100;

    for (row = 0; row < iconPanels.GetLength(0); row++)
    {
        for (col = 0; col < iconPanels.GetLength(1); col++)
        {
            diff = Math.Abs(control.Left - iconPanels[row, col].left);
            if (diff < colDist)
            {
                colDist = diff;
                nearestCol = col;
            }
            diff = Math.Abs(control.Top - iconPanels[row, col].top);
            if (diff < rowDist)
            {
                rowDist = diff;
                nearestRow = row;
            }
        }
    }
    control.Left = iconPanels[nearestRow, nearestCol].left;
    control.Top = iconPanels[nearestRow, nearestCol].top;
}

2 个答案:

答案 0 :(得分:1)

您可能希望这些位置标记保持不变,因此这是罕见的情况之一,我将使用

using ( Graphics G = theParentContainer.CreateGraphics()) 
       foreach(Rectangle rect in yourPositions) G.DrawRectangle(Pens.Red, rect);  

在跌落后或离开控制器等后清理它们......通过调用theParentContainer.Invalidate();

这假设您知道可能的位置并可以创建

List<Rectangle> yourPositions = new List<Rectangle>();
抱着他们。

众所周知;-)使用Graphics实例化的Control.CeateGraphics对象创建的图形不会持久存在,并会在下一个Paint事件中消失。但对于这样的交互式辅助图形,这是完美的。其他例子是橡皮带绘图或光标跟踪..

答案 1 :(得分:0)

在您希望高举的控件上订阅Paint事件。

private void highlightControl_Paint(object sender, System.Windows.Forms.PaintEventArgs e) {

    if(mouse is over or other control is over) { 
        Graphics g = e.Graphics;
        g.FillRectangle(Brushes.Red, 0, 0, this.Width, this.Height);
    }       
}