I'll take these one by one.
1. They get close enough to the corals because they hitch on them. In the ocean, I am pretty sure they also hitch on them, but in the ocean there are tons of corals for the seahorses to hitch on, so they don't spend enough time hitched on one coral to really irritate it. In our tanks, they don't have nearly as many choices, so the corals will be hitched on often enough to irritate them into stinging. That is my understanding of it, at least.
2. It is worth noting that all the pictures I have seen of wild seahorses show them hitching on sponges, seagrass, gorgonians, or macroalgae; it may well be that seahorses learn to avoid them in the wild after watching unlucky siblings die (it has been shown that seahorses can learn from observing one another). Pipefish are another matter entirely: some pipefish swim in the water column and never come into contact with corals or anemones, whereas others, like Dragonface Pipefish, slither along on the corals. Dragonface pipefish don't seem to get stung by corals. I think their modus operandi just doesn't irritate corals like seahorses hitching does. They might also be more active than seahorses. I think they are perhaps slightly better swimmers.
3. The habitat really depends on the seahorse in question. Some seahorses, like Hippocampus zosterae and Hippocampus kuda, are found among sargassum, macro algae, and seagrass, but not in reefs. Others, like Hippocampus barbouri, live primarily on the reef. I don't have personal experience with them, but I suspect that H. barbouri and other reef-dwelling seahorses would know which corals to avoid, given that the corals were ones they had encountered before. The wild caught ones, at least. Captive Bred seahorses are another matter; they would not have learned to avoid any corals or anemones because they have never encountered them before.
One last thing I should mention is that not all corals are dangerous for seahorses. All corals can potentially hurt/kill seahorses, but there are a decent number of exceptions. Gorgonians and sponges are generally safe for seahorses. There are some sponges that will release toxic chemicals when irritated, though, so those ought to be avoided (and not just for seahorses, either). Most soft corals are also seahorse-safe. The corals that you should generally avoid mixing with seahorses are mostly SPS and LPS. And again, pipefish are a different matter. Pipefish, like Mandarin Dragonets, will typically do just fine in a suitably large typical reef tank.