In addition to getting rid of the adult heartworms, veterinarians will also attack the microfilaria, using Ivermectin, which can also be used as a preventative treatment for heartworms.
Generally, using preventatives when there is a known infection is unsafe, since killing many worms at once can overwhelm a dog.