There are actually a lot of threads about this if you use the search bar.
This is one of the best (including example code by the JPearman). I linked JPearman’s example, but the rest of the thread could also probably be helpful:
This is a post with a lot of links in it, some with other example codes that would probably be helpful.