This is done by a provision in the agreement that the shareholders have “a right of first refusal” to purchase any shares being sold, before the shares can be offered to outside sources.
Shareholder agreements can also ensure ongoing control of the company.