This could probably be fixed by tracking whether the mousedown event was started inside or outside the dialog, and only close the dialog if the mousedown started outside it.
SQL in itself is not the weak point in this case (or any of the other cases of a successful SQLi attack). The problem is the treatment of user-controllable input data and using that data as part of a SQL query without properly sanitising/escaping special characters first.