// Make sure we clicked the mouse button and // have a starting coordinate. if (m_nStartX != -1)
{ // Get the graphcis object from this window. Graphics g = Graphics.FromHwnd(Handle); // Check to see if we need to restore the // screen from a previous rectangle draw. if (m_nLastX != -1) { // Create a rectangle with which to clip. // Note that we are 3 pixels to the left // and 3 pixels to the right so that we // can take the width of the line into // account. Rectangle rc = new Rectangle(m_nLastX-3, m_nLastY-3, m_nLastWidth+6, m_nLastHeight+6); g.SetClip(rc); g.DrawImage(m_objBitmap, 0, 0); g.ResetClip(); } // Here we set some local variables just // in case we have to swap the values. int nStartX = m_nStartX; int nStartY = m_nStartY; // Get and record our current mouse position. int nEndX = e.X; int nEndY = e.Y; // Calculate width and height. int nWidth = Math.Abs(nStartX - nEndX); int nHeight = Math.Abs(nStartY - nEndY); // We may need to swap values if user went // left from the start position. if (nEndX < nStartX) { int i = nStartX; nStartX = nEndX; nEndX = i; } // We may need to swap values if user went // up from the start position. if (nEndY < nStartY) { int i = nStartY; nStartY = nEndY; nEndY = i; } // Draw the rectangle. g.DrawRectangle(new Pen(Color.Black, 3), nStartX, nStartY, nWidth, nHeight); // Record the operation so that we can restore // when the mouse moves, and also give values // to the EndCapture method. m_nLastX = nStartX; m_nLastY = nStartY; m_nLastWidth = nWidth; m_nLastHeight = nHeight;